Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a module before it has finished parsing?

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
    
like image 389
gak Avatar asked Feb 23 '09 10:02

gak


1 Answers

try: supports an else: clause

try:
    from skynet import SkyNet

except ImportError:
    class SelfAwareSkyNet():
        pass

else:
    class SelfAwareSkyNet(SkyNet):
        pass
like image 94
Andrew Dalke Avatar answered Sep 18 '22 08:09

Andrew Dalke