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

Brett Cannon brett at python.org
Fri Apr 20 19:09:55 CEST 2007


On 4/19/07, Steven Bethard <steven.bethard at gmail.com> wrote:
> 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__'].
>

Yeah, I figured you would.  =)

> > 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__
>     foo
>     >>> mod.__main__
>     'foo'
>
> 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.

That's right, and that is the problem.  That would mean if __main__
was false but then overwritten by a function or something, it suddenly
became true.  It isn't a problem in terms of whether the code will
run, but whether the expected semantics will occur.

-Brett



More information about the Python-ideas mailing list