suppressing import errors

David Riley fraveydank at gmail.com
Tue Nov 15 12:57:11 EST 2011


On Nov 15, 2011, at 12:35 PM, Andreea Babiuc wrote:

> 
> 
> On 15 November 2011 17:24, Chris Kaynor <ckaynor at zindagigames.com> wrote:
> As with any Python code, you can wrap the import into a try: except block.
> 
> try:
>  import badModule
> except:
> 
>  
>  pass # Or otherwise handle the exception - possibly importing an
> alternative module.
> 
> 
> Hmm, I know this might sound silly, but if it fails I still want to import the module and disable those lines of code that are related to the reason while the module failed to be imported in the first place.  Even if that makes the code not 100% correct.
> 
> Does that make sense ?

It makes sense.  It probably also makes sense to only do an "except ImportError", since if there are other errors (say, syntax errors in a module you're trying to import, rather than its absence, you probably want to know about it.

To disable code that won't work without the module you're trying to import, you can always set flags in your module.  For example, I've got a project at work that can use a variety of communications interfaces, including using PySerial for serial port comms.  But if someone doesn't have PySerial installed, I want it to fail gracefully and just not support serial.  So I can do the following:


try:
   import serial
   _serial_enabled = True
except ImportError:
   print("PySerial not installed - serial ports not supported!")
   _serial_enabled = False


And then elsewhere in my module, I can check the value of _serial_enabled to see if I should e.g. list the serial ports in available communications interfaces.

Of course, if there's some other error in PySerial (maybe I installed a broken version with a syntax error?), that error will get propagated up, which is a good thing, because I'd rather know that PySerial is broken than just have it tell me it's not installed (which is what would happen if I simply caught all exceptions).  Your mileage may vary.

- Dave




More information about the Python-list mailing list