Import into specified namespace

Alex Martelli aleaxit at yahoo.com
Wed Sep 8 13:03:07 EDT 2004


Fritz Bosch <uthand at hotmail.com> wrote:
   ...
> __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

Why not sys.modules['sys'] = mydic instead of trying to rebind
sys.__dict__?   You can't affect those other modules which have ALREADY
imported sys, yourself included (but as for you, you can remedy that
easily -- sys = sys.modules['sys'] = mydic...), but otherwise you should
be OK.  sys.__dict__.update(mydic) as the last statement might also be
an alternative (and if it works for your purposes, it's cleaner than
rebinding sys.modules['sys']!-).


Alex



More information about the Python-list mailing list