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.pymodule, check if theskynetmodule is available, and simply pass or create a stub class. This will cause DRY ifselfaware.pyis imported multiple times. -
Within
selfaware.pyhave the class defined withing thetryblock. e.g.:try: from skynet import SkyNet class SelfAwareSkyNet(SkyNet): pass except ImportError: class SelfAwareSkyNet(): pass
You could use:
This works only if the implementation do not differ.
Edit: New solution after comment.