[Python-ideas] PEP for executing a module in a package containing relative imports (original) (raw)

Christian Heimes lists at cheimes.de
Sun Apr 22 20:15:43 CEST 2007


Steven Bethard wrote:

I think this PEP now needs to explicitly state that keeping the "am I the main module?" idiom as simple as possible is not a goal. Because everything I've seen (except for the original proposals in the PEP) are substantially more complicated than the current::

if name == 'main':

I'm proposing the following changes:

I guess I don't understand why we wouldn't be willing to put up with a new module attribute or builtin to minimize the boilerplate in pretty much every Python application out there.

Why bother with the second price when you can win the first prize? In my opinion a main() function makes live easier than a main module level variable. It's also my opinion that the main code should be in a function and not in the body of the module. I consider it good style because the code is unit testable (is this a word? g) and callable from another module while code in the body is not accessable from unit tests and other scripts.

I know that some people are against main(argv) but I've good reasons to propose the argv syntax. Although argv is available via sys.argv I like the see it as an argument for main() for the same reasons I like to see main. It makes unit testing and calls from another module possible. W/o the argv argument is harder to change the argument in unit tests.

Now for some syntactic sugar and a dream of mine:

@argumentdecorator(MyOptionParserClass) def main(egg, spam=5): pass

The argumentdecorator function takes some kind of option parser class that is used to parse argv. This would allow nice code like

main(('mainscript.py', '--eggs 5', '--no-spam'))

Christian



More information about the Python-ideas mailing list