break in a module

Ben Finney ben+python at benfinney.id.au
Tue Jun 14 20:43:36 EDT 2011


Eric Snow <ericsnowcurrently at gmail.com> writes:

> When you want to stop execution of a statement body early, for flow
> control, there is a variety ways you can go, depending on the context.
>  Loops have break and continue.  Functions have return.  Generators
> have yield (which temporarily stops execution).  Exceptions sort of
> work for everything, but have to be caught by a surrounding scope, and
> are not necessarily meant for general flow control.
>
> Is there a breaking flow control mechanism for modules?

Since your nominated use case is only to do it when ‘__name__ ==
'__main__'’, you could call ‘sys.exit()’.

> With modules I sometimes have code at the beginning to do some small
> task if a certain condition is met, and otherwise execute the rest of
> the module body.

I don't see how your use case needs to skip executing the rest of the
module code.

> Here's my main use case:
>
>   """some module"""
>
>   import sys
>   import importlib
>   import util  # some utility module somewhere...
>
>   if __name__ == "__main__":
>       name = util.get_module_name(sys.modules[__name__])
>       module = importlib.import_module(name)
>       sys.modules[__name__] = module
>   else:
>       # do my normal stuff at 1 indentation level

What “normal stuff” is the module doing that shouldn't be done when the
module is ‘__main__’? I can't see what the use case is for.

As you're no doubt aware, the normal pattern is to execute all the
“normal stuff” for a module unconditionally, which creates all the
objects in the module namespace (its imports, classes, functions, and
other attributes) without side effects; then check if the module is
‘__main__’ at the *end*.

So you'll probably need to be more specific about why your use case
differs from that.

-- 
 \         “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\    Brain, but if the plural of mouse is mice, wouldn't the plural |
_o__)                      of spouse be spice?” —_Pinky and The Brain_ |
Ben Finney



More information about the Python-list mailing list