Eric Snow wrote:
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.
The answer would depend on exactly what "normal stuff" you expect your module to do if it's not being run as a script (which is what your `__name__ == '__main__'` check tests for). A typical module will define it's appropriate attributes, functions, classes, and so on at module scope. It will then end with a test to see if it's being run as a script, and then do the appropriate thing. This allows modules to be imported separately from being executed as scripts.
Your sample code makes it hard to understand the use case, especially since if you want this hypothetical "module break" to stop executing the module, then your `__name__ == '__main__'` test basically does nothing useful (it fiddles with some modules -- especially since it appears to be they very module that is being executed -- and then quits).
At a more general level, the idea of a "module break" doesn't make much sense. Modules are just collections of things; they can include some direct code, but typically consist of mostly definitions. Modules can interact with each other, be called recursively, etc., and so at an arbitrary point saying, "break out of this module" doesn't have a great deal of meaning.
-- Erik Max Francis && [email protected] && 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
