[Python-ideas] PEP for executing a module in a package containing relative imports
Brett Cannon
brett at python.org
Sun Apr 22 20:44:56 CEST 2007
On 4/22/07, Christian Heimes <lists at cheimes.de> wrote:
> 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:
>
> * sys.main is added which contains the dotted name of the main script.
> This allows code like:
>
> if __name__ == sys.main:
> ...
>
> main_module = sys.modules[sys.main]
>
> * __name__ is never mangled and contains always the dotted name of
> the current module. It's not set to '__main__' any more.
That can't be true. If I am in the directory /spam but I execute the
file /bacon/code.py, what is the name of /bacon/code.py supposed to
be? It makes absolutely no sense unless sys.path happens to have
either / or /bacon. This is why I wondered out loud if setting
whatever attribute that is chosen not to __main__ should only be done
with '-m' as that keeps it simple and clear instead of having to try
to reverse-engineer a file's __name__ attribute.
>You can
> get the current module object with
>
> this_module = sys.modules[__name__]
>
> * I'm against sys.modules['__main__] = main_module because it may
> cause ugly side effects with reload.
I assume that key is a string? There is a single quote that is not closed off.
> The same functionality is
> available with sys.modules[sys.main]. The Zen Of Python says that
> there should be one and only one obvious way.
>
> > 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.
People can stop wishing for this. I am not going to be writing a PEP
supporting this. I don't like it; never have. I like how Python
handles things currently in terms of relying on how module are
executed linearly.
I am totally fine if people propose a competing PEP or try to
resurrect PEP 299, but I am not going to be the person who does that
leg work.
-Brett
More information about the Python-ideas
mailing list