Import into specified namespace

Fritz Bosch uthand at hotmail.com
Wed Sep 8 18:44:00 CEST 2004


Hi experts

Is is possible to import/manipulate a module such that
I can supply its __dict__?

I want to supply my own dict subclass object to be filled
by the import, e.g. a class like:

>>> class MyModuleDict(dict):
... 	def __setitem__(self,name,val):
... 		print name, val
... 		dict.__setitem__(self,name,val)

__dict__ is a readonly attribute, so I can't change it after
the import, i.e. the following doesn't work:

>>> import sys
>>> mydic = MyModuleDict()
>>> mydic.update(sys.__dict__)
>>> sys.__dict__ = mydic
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: readonly attribute

I have experimented with new.module(), __import__(),
imp.*, exec/eval/execfile+globals/locals but to no avail.

Is there any way to do this?

Thanks
Fritz



More information about the Python-list mailing list