On Tue, Jun 14, 2011 at 5:51 PM, Erik Max Francis <m...@alcyone.com> wrote: > Ethan Furman wrote: >> >> To me, too -- too bad it doesn't work: >> >> c:\temp>\python32\python early_abort.py >> File "early_abort.py", line 7 >> return >> ^ >> SyntaxError: 'return' outside function > > Nor should it. There's nothing to return out of. >
Perhaps we have a misunderstanding then. The contents of a module file are the body of the module definition. Like the body of any other complex statement, that body is going to get executed [1]. Some of the complex statements have keywords that let you break out of that execution, like break and continue in loops. Some do not. However, there is most certainly something out of which to return, the execution of the module body. That fact that the functionality is not there does not mean it has to stay that way. It may just be that no one has thought to add it. I don't agree that it's a bad idea. I have a use case. The alternative is unappealing to me. That's how new features are born. I apologize if my example was unclear. I kept it pretty simple. I expect using __main__ was misleading. However, this is by no means the only use case. In general it would be nice to do some checks up front and decide whether or not to continue executing the module, rather than waiting until the end to decide: if condition_1: ... return if condition_2: ... return # now do my expensive module stuff # finally handle being run as a script if __name__ == "__main__": ... The only ways that I know of to accomplish this currently is either by putting everything inside if-else blocks, or raise some kind of ImportBreak exception and catch it in an import hook. I would rather not use either one. The more levels of indentation in a module, the harder it is to follow. And exceptions really should not be involved in execution flow control, but in the handling of abnormal situations instead. Considering that other complex statements have special flow control statements, I don't see why modules shouldn't either. -eric [1] During import the module gets compiled and the result is exec'ed in the context of the __dict__ of a new ModuleType object. That module object is then placed in sys.modules and bound to the name you have in the import statement in the module from which you issued that statement. Remember, the module is executed once, when the import statement is executed. That is when the module flow control would happen. > -- > Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis > There is _never_ no hope left. Remember. > -- Louis Wu > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list