Using the ImportError exception

An alternative to an if statement is to use a try statement to locate a candidate's implementation. This technique works well when there are different distributions. Often, a platform-specific distribution may include files that are unique to the platform.

In Chapter 16, The Logging and Warning Modules, we showed you this design pattern in the context of providing warnings in the event of a configuration error or problem. In some cases, tracking down variant configurations doesn't deserve a warning, because the variant configuration is a design feature.

Here's __init__.py for a some_algorithm package, which chooses an implementation based on the availability of the module files within the package:

try: 
    from some_algorithm.long_version import * 
except ImportError as e: 
    from some_algorithm.short_version import * 

This depends on having two distinct distributions that will include either the some_algorithm/long_version.py file or the some_algorithm/short_version.py file. If the some_algorithm.long_version module is not found, then some_alogirithm.short_version will be imported. The content of the implementation modules doesn't change from what was shown in the preceding code block. Only the __init__.py module will change.

Creating variant distributions is outside the scope of this book. The Python Packaging Authority, PyPA, has documentation showing how platform-specific wheel and egg files can be created.

This try/except technique doesn't scale to more than two or three alternative implementations. As the number of choices grows, the except blocks will become very deeply nested. 

Let's see how to design a main script and the main module.

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

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