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:
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
try: supports an else: clause
try:
from skynet import SkyNet
except ImportError:
class SelfAwareSkyNet():
pass
else:
class SelfAwareSkyNet(SkyNet):
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With