[Python-ideas] PEP for executing a module in a package containing relative imports

Steven Bethard steven.bethard at gmail.com
Fri Apr 20 07:56:09 CEST 2007

On 4/19/07, Brett Cannon <brett at python.org> wrote:
> Let me know what you think.  I especially want to hear which proposal
> people prefer; the one in the PEP or the one in the Open Issues
> section.  Plus I wouldn't mind suggestions on a title for this PEP.

As you've probably already guessed, I prefer the::

    if __main__:

version. I don't think I've ever used sys.modules['__main__'].

> Transition Plan
> ===============
> Using this solution will not work directly in Python 2.6.  Code is
> dependent upon the semantics of having ``__name__`` set to
> ``'__main__'``.  There is also the issue of pre-existing global
> variables in a module named ``__main__``.

Could you explain a bit why __main__ couldn't be inserted into modules
before the module is actually executed? E.g. something like::

    >>> module_text = '''\
    ... __main__ = 'foo'
    ... print __main__
    ... '''
    >>> import new
    >>> mod = new.module('mod')
    >>> mod.__main__ = True
    >>> exec module_text in mod.__dict__
    >>> mod.__main__

I would have thought that if Python inserted __main__ before any of
the module contents got exec'd, it would be backwards compatible
because any use of __main__ would just overwrite the default one.

I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
        --- Bucky Katt, Get Fuzzy

More information about the Python-ideas mailing list