How to exit the module before its completion?

I have a module that imports a module, but in some cases the imported module may not exist. After importing a module, there is a class that inherits from the class the imported module. If I were to catch an exception ImportErrorif the module does not exist, how can I stop Python from parsing the rest of the module? I am open to other solutions if this is 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 thing I can do is:

  • Before importing a module, selfaware.pycheck if the module is available skynet, and simply pass or create a stub class. This will cause DRY if it selfaware.pyis imported multiple times.
  • selfaware.py , try. :.

    try:
        from skynet import SkyNet
        class SelfAwareSkyNet(SkyNet):
            pass
    except ImportError:
        class SelfAwareSkyNet():
            pass
    
+5
2

:

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

class SelfAwareSkyeNet(inherit_from):
    pass

, .

: .

+2

try: else:

try:
    from skynet import SkyNet

except ImportError:
    class SelfAwareSkyNet():
        pass

else:
    class SelfAwareSkyNet(SkyNet):
        pass
+8

All Articles