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. -- http://mail.python.org/mailman/listinfo/python-list