views:

322

answers:

4

I have a module that imports a module, but in some cases the module being imported may not exist. After the module is imported there is a class inherits from a class the imported module. If I was to catch the ImportError exception in the case the module doesn't exist, how can I stop Python from parsing the rest of the module? I'm open to other solutions if that's not possible.

Here is a basic example (selfaware.py):

try:
    from skynet import SkyNet
except ImportError:
    class SelfAwareSkyNet():
        pass
    exit_module_parsing_here()

class SelfAwareSkyNet(SkyNet):
    pass

The only ways I can think to do this is:

  • Before importing the selfaware.py module, check if the skynet module is available, and simply pass or create a stub class. This will cause DRY if selfaware.py is imported multiple times.
  • Within selfaware.py have the class defined withing the try block. e.g.:

    try:
        from skynet import SkyNet
        class SelfAwareSkyNet(SkyNet):
            pass
    except ImportError:
        class SelfAwareSkyNet():
            pass
    
A: 

You could use:

try:
   from skynet import SkyNet
   inherit_from = SkyNet
except ImportError:
   inherit_from = object

class SelfAwareSkyeNet(inherit_from):
    pass

This works only if the implementation do not differ.

Edit: New solution after comment.

hyperboreean
sys.exit() will exit the application, I want it to continue with a different definition of the class.
Gerald Kaszuba
+2  A: 

This should do the trick:

try:
    from skynet import SkyNet
except ImportError:
    class SelfAwareSkyNet():
        pass
else:
    class SelfAwareSkyNet(SkyNet):
        pass
Constantin
+6  A: 

try: supports an else: clause

try:
    from skynet import SkyNet

except ImportError:
    class SelfAwareSkyNet():
        pass

else:
    class SelfAwareSkyNet(SkyNet):
        pass
Andrew Dalke
+1  A: 

Most simple solution:

try:
    from skynet import SkyNet
    parent = SkyNet
except ImportError:
    parent = object

class SelfAwareSkyNet(parent):
    pass

Note: Untested but you get the idea.

Aaron Digulla