[Python-ideas] breaking out of module execution
mal at egenix.com
Tue Apr 24 22:20:38 CEST 2012
Georg Brandl wrote:
> On 24.04.2012 21:58, M.-A. Lemburg wrote:
>> Antoine Pitrou wrote:
>>> On Tue, 24 Apr 2012 13:23:53 -0600
>>> Eric Snow <ericsnowcurrently at gmail.com>
>>>> 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
>>> I think good practice should lead you to put your initialization code
>>> in a dedicated function that you call from your module toplevel. In
>>> this case, breaking out of execution is a matter of adding a return
>> True, but that doesn't prevent import from being run, functions and
>> classes from being defined and resources being bound which are not
>> going to get used.
> What's wrong with an if statement on module level, if you even care
> about this?
You'd have to indent the whole module. Been there, done that, doesn't
look nice :-)
>> Think of code like this (let's assume the "break" statement is used
>> for stopping module execution):
>> # MyModule
>> ### Try using the fast variant
>> from MyModule_C_Extension import *
>> except ImportError:
>> # Stop execution of the module code object right here
>> ### Ah, well, so go ahead with the slow version
>> import os, sys
>> from MyOtherPackage import foo, bar, baz
>> class MyClass:
>> def MyFunc(a,b,c):
>> def main():
>> if __name__ == '__main__':
> There's a subtle bug here that shows that the proposed feature has its
> awkward points: you probably want to execute the "if __name__ == '__main__'"
> block in the C extension case as well.
No, you don't :-) If you would have wanted that to happen, you'd
put the "if __name__..." into the else: branch.
You think of the "break" as having the same functionality as a "return"
in a function.
If reusing a statement is too much trouble, the same functionality
could be had with an exception that get's caught by the executing
Professional Python Services directly from the Source (#1, Apr 24 2012)
>>> Python/Zope Consulting and Support ... http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/
2012-04-28: PythonCamp 2012, Cologne, Germany 4 days to go
::: Try our new mxODBC.Connect Python Database Interface for free ! ::::
eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
Registered at Amtsgericht Duesseldorf: HRB 46611
More information about the Python-ideas