Abort module execution in Python

I would like to stop evaluating the imported module without stopping the entire program.

Here is an example of what I want to achieve:

main.py

print('main1') import testmodule print('main2') 

testmodule.py

 print(' module1') some_condition=True if some_condition: exit_from_module() # How to do this? print(' module2') # This line is not executed. 

Expected Result:

 main1 module1 main2 
+7
source share
3 answers

Unable to stop module execution. You can throw an exception, but then you need your importing module. Maybe just refactoring:

 print(' module1') some_condition = True if not some_condition: print(' module2') 

Update. It would be even better to change your module to define only functions and classes, and then call one of them for the caller to do the work they have to do.

If you really want to do all this work during import (remember, I think it would be better not to do this), then you can change your module in this way:

 def _my_whole_freaking_module(): print(' module1') some_condition = True if some_condition: return print(' module2') _my_whole_freaking_module() 
+6
source

My main.py looks like this:

 print 'main 1' try: import my_module except ImportError: pass print 'main 2' 

and my_module.py looks like this:

 print 'module 1' if True: raise ImportError else: pass print 'module 2' 

output,

 main 1 module 1 main 2 
+3
source

You can wrap the module code inside a function, for example:

 def main(): print(' module1') some_condition=True if some_condition: return print(' module2') main() 
+2
source

All Articles