Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7655

Re: break in a module

From Ben Finney <ben+python@benfinney.id.au>
Newsgroups comp.lang.python
Subject Re: break in a module
References <mailman.237.1308090506.11593.python-list@python.org>
Date 2011-06-15 10:43 +1000
Message-ID <87wrgnsz47.fsf@benfinney.id.au> (permalink)
Organization Unlimited download news at news.astraweb.com

Show all headers | View raw


Eric Snow <ericsnowcurrently@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

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

break in a module Eric Snow <ericsnowcurrently@gmail.com> - 2011-06-14 16:28 -0600
  Re: break in a module Erik Max Francis <max@alcyone.com> - 2011-06-14 16:51 -0700
  Re: break in a module Ben Finney <ben+python@benfinney.id.au> - 2011-06-15 10:43 +1000

csiph-web