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 theskynet
module is available, and simply pass or create a stub class. This will cause DRY ifselfaware.py
is imported multiple times. Within
selfaware.py
have the class defined withing thetry
block. e.g.:try: from skynet import SkyNet class SelfAwareSkyNet(SkyNet): pass except ImportError: class SelfAwareSkyNet(): pass