[Python-ideas] breaking out of module execution

Eric Snow ericsnowcurrently at gmail.com
Tue Apr 24 21:23:53 CEST 2012

In a function you can use a return statement to break out of execution
in the middle of the function.  With modules you have no recourse.
This is akin to return statements being allowed only at the end of a

There are a small number of ways you can work around this, but they
aren't great.  This includes using wrapper modules or import hooks or
sometimes from-import-*.  Otherwise, if your module's execution is
conditional, you end up indenting everything inside an if/else

Proposal: introduce a non-error mechanism to break out of module
execution.  This could be satisfied by a statement like break or
return, though those specific ones could be confusing.  It could also
involve raising a special subclass of ImportError that the import
machinery simply handles as not-an-error.

This came up last year on python-list with mixed results. [1]
However, time has not dimmed the appeal for me so I'm rebooting here.

While the proposal seems relatively minor, the use cases are not
extensive. <wink>  The three main ones I've encountered are these:

1. C extension module with fallback to pure Python:

      from _extension_module import *
  except ImportError:
      break  # or whatever color the bikeshed is

  # pure python implementation goes here

2. module imported under different name:

  if __name__ != "expected_name":
      from expected_name import *

  # business as usual

3. module already imported under a different name:

  if "other_module" in sys.modules:
      exec("from other_module import *", globals())

  # module code here



[1] http://mail.python.org/pipermail/python-list/2011-June/1274424.html

More information about the Python-ideas mailing list