[Python-Dev] PEP 395: Module Aliasing

Nick Coghlan ncoghlan at gmail.com
Sun Mar 6 01:33:28 CET 2011


On Sun, Mar 6, 2011 at 4:11 AM, Ron Adam <rrr at ronadam.com> wrote:
> Adding a second references to the '__main__' module begins to blur the
> purpose of sys.modules from being a place to keep imported modules to a
> place that also has some ordering information.  (Practicality over purity?,
> Or an indication of what direction to go in?)
>
> And, if you ask for keys, items, or values, you will need to filter out
> '__main__' to avoid the double reference.
>
> So I was thinking, what if we make sys.modules a little smarter.  The
> negative of that is, it would no longer be a simple dictionary object.
>
> First idea ...
>
> Add a __main__ attribute to sys.modules to hold the name of the main module.
>
> Override modules.__setitem__, so it will catch '__main__' and set
> modules.__main__ to the name of the module, and put the module in under its
> real name instead of '__main__'.
>
> Override modules.__getitem__, so it will catch '__main__' and return
> self[self.__main__].
>
> Then keys(), values(), and items(), will not have the doubled main module
> references in them.
>
> The name of the main module is easy to get.  ie... sys.modules.__main__
>
> sys.modules[__name__] will still return the correct module if __name__ ==
> "__main__".

That's quite an interesting idea - I hadn't even considered the
implications of double counting the affected module when iterating
over sys.modules in some fashion. That said, dropping `__main__` from
the iteration might confuse existing code, so it may be better to have
the lookup go the other way (i.e. define __missing__ on the dict
subclass and return sys.modules['__main__'] if the key matches
sys.modules.__main__).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list