[Python-ideas] descriptors outside of classes

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Mar 31 04:07:38 CEST 2011


Eric Snow wrote:
> For imports you have to go through __import__.  So a __module_class__ 
> would dictate which class for import to use.  By default it would be 
> types.ModuleType.  Makes sense.

There's one tricky point, though -- you need a module object
before you can execute the module's code, and it's the module's
code that creates the __moduleclass__ entry.

What should probably happen is that a standard module object
gets created initially, and then after executing the module
body, replace the module's __class__ with the __moduleclass__,
if any.

You can't currently do this in Python code, because it won't
let you change the __class__ of a builtin module object. So
either that restriction would have to be lifted, or the
machinery implementing this would have to be written in C.

An alternative (which is what PyGUI currently does) is to
create a new module object of the specified class, copy the
__dict__ of the original module into it, and then replace
the entry in sys.modules. This would be second-best, though,
because it would mean that if the module imported itself,
it would end up with the old module object instead of the
new one. The same thing would also happen to any other
modules that imported the first module while it was still
loading.

-- 
Greg



More information about the Python-ideas mailing list