[Python-Dev] Data Descriptors on module objects (was Re: draft PEP: Trace
and Profile Support for Threads)
Phillip J. Eby
pje@telecommunity.com
Thu, 24 Apr 2003 22:01:52 -0400
At 07:22 PM 4/24/03 -0400, Aahz wrote:
>Data descriptors on module objects.
If you *really* need them, you can have them.
from types import ModuleType
import time, sys
class ModuleWithDescriptor(ModuleType):
bar = property(lambda self: time.time())
moduleFoo = ModuleWithDescriptor()
# named module must be importable, but not yet imported;
# parent package must be in sys.modules
moduleFoo.__name__ = "mypackage.foo"
sys.modules['mypacakge.foo'] =
reload(moduleFoo)
import mypackage.foo
# watch the time change...
print mypackage.foo.bar
print mypackage.foo.bar
I *love* new-style classes. I use the trick above for lazy module
importation; a subclass of ModuleType that doesn't import itself until the
first time a __getattribute__ occurs.