Define type of 'module' object that is imported

Zachary Pincus zpincus at stanford.edu
Sat Apr 22 13:32:28 EDT 2006


>> I would like a given module to be created as an
>> instance of that particular subclass on import, so that if I do:
>>
>> import foo
>> type(foo)
>>
>> I get <type 'myModule'> instead of <type 'module'>.
>>
>> Is there any way to effect this? Something like __metaclass__  
>> = ...  but
>> at the beginning of a module instead of at the beginning of a class?
>
> Would be interesting to know about the motivation. Is foo just your  
> own
> module or "any" module.

No, just one particular module that needs to do some slow things.
I'd like for a user to just be able to type
"import foo"
and have the foo module's type be some special type. None of the  
options below really allow this to happen with one step. It would be  
more like "import lazyFoo; import foo".

What I'm doing now is in 'foo.py' performing surgery a la:
sys.modules[__name__] = MyModuleClass(...)
but that's ugly, and can break the reload mechanism, and causes some  
other troubles.
I would like to do:
sys.modules[__name__].__class__ = MyModuleClass
but that fails because the module is "not a heap type" or something.

I have also tried:
sys.modules[__name__].__getattribute__ = MethodType(myGetattr,  
sys.modules[__name__], ModuleType)
but the custom __getattribute__ never gets called.

Hmm, oh well.

Zach

> * you can replace __import__
> * you can set sys.modules['foo']=mymod   (in sitecustomize.py ? )
> * your module can be a class instance as well in newer pythons (2.2 
> +?);
>    => you can set sys.modules['foo']=Foo()   # Foo having  
> properties ...
> * simply import certain expensive modules only ad-hoc
> * maybe you don't need it as module at all, but an instance. or you
> avoid pre-computing things in global namespace.
> ...




More information about the Python-list mailing list