[Python-ideas] breaking out of module execution

Michael Foord 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
> function.
>
> 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
> statement.
>
> 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.
>
>

For what it's worth I've wanted this a couple of times. There are always
workarounds of course (but not particularly pretty sometimes).

Michael



> 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:
>
>  try:
>      from _extension_module import *
>  except ImportError:
>      pass
>  else:
>      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 *
>      break
>
>  # business as usual
>
> 3. module already imported under a different name:
>
>  if "other_module" in sys.modules:
>      exec("from other_module import *", globals())
>      break
>
>  # module code here
>
> Thoughts?
>
> -eric
>
>
> [1] http://mail.python.org/pipermail/python-list/2011-June/1274424.html
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 

http://www.voidspace.org.uk/

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...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120424/09111968/attachment.html>


More information about the Python-ideas mailing list