[Python-3000] PEP to change how the main module is delineated

Josiah Carlson jcarlson at uci.edu
Tue Apr 24 05:19:40 CEST 2007


"Guido van Rossum" <guido at python.org> wrote:
> 
> On 4/22/07, Brett Cannon <brett at python.org> wrote:
> > This PEP is to change the ``if __name__ == "__main__": ...`` idiom to
> > ``if __name__ == sys.main: ...``  so that you at least have a chance
> > to execute module in a package that use relative imports.
> >
> > Ran this PEP past python-ideas.  Stopped the discussion there when too
> > many new ideas were being proposed.  =)  I have listed all of them in
> > the Rejected Ideas section, although if overwhelming support for one
> > comes forward the PEP can shift to one of them.
> 
> I'm -1 on this and on any other proposed twiddlings of the __main__
> machinery. The only use case seems to be running scripts that happen
> to be living inside a module's directory, which I've always seen as an
> antipattern. To make me change my mind you'd have to convince me that
> it isn't.

"Guido's Decision" on PEP 328 offers a module/package hierarchy where
'from ..subpackage2.moduleZ import eggs' is offered as a valid use-case. 
It does not specify the name of subpackage1/moduleX.py (that is
performing the import), but there is the somewhat hidden implication
that if it were executed directly from the command line, it would not be
allowed (but this is only revealed in understanding the implications of
__name__ == '__main__' with regards to the PEP).

Personally, I would much prefer a change in __name__ == sys.main than
having to hack relative imports to offer __name__s like
__main__..subpackage.moduleZ, or even 'import
sys;sys.path.insert(1, os.path.basename(os.path.basename(__file__)))',
the latter of which I already do in every script in a codebase laid out
like...

    /.../packageX/
        __init__.py
        application1/
            __init__.py
            script1.py
            ...
            tests/
                ...
        application2/
            __init__.py
            script5.py
            ...
            tests/
                ...
        ...
        shared/
            __init__.py
            shared1.py
            ...

The preamble to properly deal with error conditions in the current path
became tiresome to place in every application path after the first few. 
I can't believe that the above is an antipattern; seems to be the
simplest way to update and distribute a group of related applications
with a simple 'svn co packageX' or 'svn up packageX'.


 - Josiah



More information about the Python-3000 mailing list