Using the warnings module

Object-oriented development often involves performing a significant refactoring of a class or module. It's difficult to get the API exactly right the very first time we write an application. Indeed, the design time required to get the API exactly right might get wasted. Python's flexibility permits us great latitude in making changes, as we learn more about the problem domain and the user's requirements.

One of the tools that we can use to support the design evolution is the warnings module. There are the following two clear use cases for warnings and one fuzzy use case:

  • Warnings should be used to alert developers of API changes; usually, features that are deprecated or pending deprecation. Deprecation and pending deprecation warnings are silent by default. These messages are not silent when running the unittest module; this helps us ensure that we're making proper use of upgraded library packages.
  • Warnings should alert users about a configuration problem. For example, there might be several alternative implementations of a module; when the preferred implementation is not available, we might want to provide a warning that an optimal implementation is not being used.
  • We might push the edge of the envelope by using warnings to alert users that the results of the computation may have a problem. From outside the Python environment, one definition of a warning says, ...indicate that the service might have performed some, but not all, of the requested functionsThis idea of an incomplete result leading to a warning is open to dispute: it may be better to produce no result rather than a potentially incomplete result.

For the first two use cases, we'll often use Python's warnings module to show you that there are correctable problems. For the third blurry use case, we might use the logger.warn() method to alert the user about the potential issues. We shouldn't rely on the warnings module for this, because the default behavior is to show a warning just once.

The value of the warnings module is to provide messages that are optional and aimed at optimizations, compatibility, and a small set of runtime questions. The use of experimental features of a complex library or package, for example, might lead to a warning. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset