Determining Python program behavior based on available imports

Python’s import statement is an executable statement like any other. This means it can be used to determine if a particular external module is available. If a module is not available for import, the program can either modify its behavior accordingly, or shut down in a graceful fashion.

For example, if a program has optional functionality that depends on an external module for some kind of I/O support, then it may make sense to allow the program to continue to run with that functionality disabled. Python’s OO model makes this easy to do, provided that the optional functionality is encapsulated in an object that can be selectively instantiated.

Here’s a simple example:

GV_use_optio = True
try:
  import OptIO
except:
  GV_use_optio = False

This code would typically appear at the top of a module with the rest of the import statements. Notice that a global variable, GV_use_optio, is initialized with a value of True. It will remain true if the import of OptIO succeeds, otherwise it will be set to False. Also, in this case there’s no check for what may have caused the problem.

The global variable would then be used later on to determine if the optional functionality should be enabled or not. Here’s one approach (somewhere further along in the code):

optio = None
if GV_use_optio:
  optio = OptIO.OptIOClass()

The local variable optio can be checked to determine if the OptIOClass object is available or if it should be skipped.

This approach can be used to control how a GUI is populated, what other modules are imported, and what objects are instantiated. It can be used to create a “ripple-down” effect througout the code, altering boths it behavior and its appearance in accordance with available imported modules.

0 Responses to “Determining Python program behavior based on available imports”



  1. Leave a Comment

Leave a comment




Follow Crankycode on WordPress.com

Little Buddy

An awesome little friend

Jordi the Sheltie passed away in 2008 at the ripe old age of 14. He was the most awesome dog I've ever known.