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.

Advertisements

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



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: