Showing configuration problems with a warning

We may have multiple implementations for a given class or module. We'll often use a configuration file parameter to decide which implementation is appropriate. See Chapter 14, Configuration Files and Persistence, for more information on this technique.

In some cases, however, an application may silently depend on whether or not other packages are part of the Python installation. One implementation may be optimal, and another implementation may be the fallback plan. This is used by a number of Python library modules to choose between optimized binary modules and pure Python modules.

A common technique is to try multiple import alternatives to locate a package that's installed. We can produce warnings that show us the possible configuration difficulties. Here's a way to manage this alternative implementation import:

import warnings

try:
import simulation_model_1 as model
except ImportError as e:
warnings.warn(repr(e))
if 'model' not in globals():
try:
import simulation_model_2 as model
except ImportError as e:
warnings.warn(repr(e))
if 'model' not in globals():
raise ImportError("Missing simulation_model_1 and simulation_model_2")

We tried one import for a module. If this had failed, we'd have tried another import. We used an if statement to reduce the nesting of exceptions. If there are more than two alternatives, nested exceptions can lead to a very complex-looking exception. By using extra if statements, we can flatten a long sequence of alternatives so that the exceptions aren't nested.

We can better manage this warning message by changing the class of the message. In the preceding code, this will be UserWarning. These are shown by default, providing users with some evidence that the configuration is not optimal.

If we change the class to ImportWarning, it will be silent by default. This provides a normally silent operation in cases where the choice of package doesn't matter to users. The typical developer's technique of running with the -Wd option will reveal the ImportWarning messages.

To change the class of the warning, we change the call to warnings.warn(), as follows:

warnings.warn(e, ImportWarning) 

This changes the warning to a class that is silent by default. The message can still be visible to developers, who should be using the -Wd option.

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

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