__main__ vs official module name: distinct module instances

Chris Angelico rosuav at gmail.com
Sun Aug 2 00:12:11 EDT 2015


On Sun, Aug 2, 2015 at 1:53 PM, Cameron Simpson <cs at zip.com.au> wrote:
> What are the implications of modifying the python invocation:
>
>  python -m cs.app.maildb
>
> to effectively do this (Python pseudo code):
>
>  M = importlib.import("cs.app.maildb")
>  M.__name__ = '__main__'
>  sys.modules['__main__'] = M
>
> i.e. import the module by name, but bind it to _both_ "cs.app.maildb" and
> "__main__" in sys.modules. And of course hack .__name__ to support the
> standard boilerplate.
>
> This would save some confusion when the module is invoked from the python
> command line and also imported by the code; it is not intuitive that those
> two things give you distinct module instances.
>
> Aside from the module's .__name__ being '__main__' even when accessed by the
> code as cs.app.maildb, are there other implications to such a change that
> would break real world code?

That's the one implication that comes to mind. It breaks the invariant
that "import X; X.__name__" should be the string form of X. But does
anything ever actually depend on that, or do things depend on the
weaker requirement that X.__name__ should be something which you can
import to get back a reference to X?

I'd support this proposal. I'm not seeing any glaring problems, and it
does have the potential to prevent bizarre problems. It would still
want to be a non-recommended course of action, though, as the change
won't (presumably) be backported - so any code that assumes that
importing its main file gives the same module as __main__ will
silently do the wrong thing on Python 2.7.

Toss it out onto -ideas and see what bounces back!

ChrisA



More information about the Python-list mailing list