suppressing import errors

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Nov 15 13:58:30 EST 2011


David Riley wrote:
> 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
>
>   
If I'm not wrong the OP wants to disable the line *in the module being 
imported*, which is kindof silly and doesn't make sense to answer his 
question.

Anreea, tell us why the module you are importing is failing and if this 
module is yours, we may provide you a proper way to handle this 
situation (though I'm pretty sure everything is in Dave's proposal).

JM
PS : @Dave there is a way to avoiding adding symbols to your global 
namespace, assign None to the module's name on import errors. Then 
before using it, just test the module bool value : if serial: 
serial.whateverMethod()



More information about the Python-list mailing list