[Python-Dev] PEP 395: Module Aliasing (original) (raw)

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