[Python-ideas] breaking out of module execution

Mark Shannon mark at hotpy.org
Tue Apr 24 22:15:57 CEST 2012


This has to be the only few feature request that can implemented by 
removing code :)
I implemented this by deleting 2 lines of code from the compiler.
M.-A. Lemburg wrote:
> Antoine Pitrou wrote:
>> On 2012年4月24日 13:23:53 -0600
>> 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.
>> 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
>> statement.
>> 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.
>> Think of code like this (let's assume the "break" statement is used
> for stopping module execution):
>> """
> #
> # MyModule
> #
>> ### Try using the fast variant
>> try:
> from MyModule_C_Extension import *
> except ImportError:
> pass
> else:
> # Stop execution of the module code object right here
> break

It will have to be "return" not "break".
>> ### 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__':
> main()
> """
>> You can solve this by using two separate modules and a top-level
> module to switch between the implementations, but that's cumbersome
> if you have more than just a few of such modules in a package.
>


More information about the Python-ideas mailing list

AltStyle によって変換されたページ (->オリジナル) /