[Python-ideas] breaking out of module execution
fuzzyman at gmail.com
Tue Apr 24 23:45:28 CEST 2012
On 24 April 2012 20:23, Eric Snow <ericsnowcurrently at gmail.com> wrote:
> 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. 
> However, time has not dimmed the appeal for me so I'm rebooting here.
For what it's worth I've wanted this a couple of times. There are always
workarounds of course (but not particularly pretty sometimes).
> 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
>  http://mail.python.org/pipermail/python-list/2011-June/1274424.html
> Python-ideas mailing list
> Python-ideas at python.org
May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas