break in a module

E

Eric Snow

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?

Regardless of the context, I've found it cleaner to use flow control
statements, like break, continue, and return, to stop execution under
some condition and then leave the rest of my code at the smaller
indentation level. For example:

for i in range(5):
if i % 2:
print("odd: %s" % i)
continue

print("even: %s" % i)

This could be written with if-else for control flow:

for i in range(5):
if i % 2:
print("odd: %s" % i)
else:
print("even: %s" % i)

Or, for functions:

def f(arg):
if not arg:
return None

print("found something: %s" % arg)
return arg

vs:

def f(arg):
if not arg:
result = None
else:
print("found something: %s" % arg)
result = arg
return result

The more levels of indentation the harder it becomes to read.
However, with the breaking flow control statements, you can mitigate
the nesting levels somewhat. One nice thing is that when doing this
you can have your default behavior stay at the smallest indentation
level, so the logic is easier to read.

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. 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

I would rather have something like this:

"""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
break

# do my normal stuff at 0 indentation level

So, any thoughts? Thanks.

-eric

p.s. I might just handle this with a PEP 302 import hook regardless,
but it would still be nice to know if there is a better solution than
basically indenting my entire module.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top