<br><br><div class="gmail_quote">On Sun, Aug 2, 2009 at 9:06 AM, Steven D'Aprano <span dir="ltr"><<a href="mailto:steve@remove-this-cybersource.com.au">steve@remove-this-cybersource.com.au</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
I was playing around with a custom mapping type, and I wanted to use it<br>
as a namespace, so I tried to use it as my module __dict__:<br>
<br>
>>> import __main__<br>
>>> __main__.__dict__ = MyNamespace()<br>
Traceback (most recent call last):<br>
  File "<stdin>", line 1, in <module><br>
TypeError: readonly attribute<br>
<br>
Why is __dict__ made read-only?</blockquote><div>to protect module type? Use .update() method:</div><div>__main.__.__dict__.update(MyNamespace())</div><div></div><div>You can create your own Module instance:</div><div>from types import ModuleType</div>
<div>m = ModuleType('modulename')</div><div></div><div>and make a sub class of ModuleType is also OK</div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;"><br>

<br>
I next thought I could change the type of the namespace to my class:<br>
<br>
>>> __main__.__dict__.__class__ = MyNamespace<br>
Traceback (most recent call last):<br>
  File "<stdin>", line 1, in <module><br>
TypeError: __class__ assignment: only for heap types<br>
<br>
Drat, foiled again!!!<br>
<br>
Okay, if I can't do this at the module level, can I at least install a<br>
custom namespace at the class level?<br>
<br>
>>> class MyNamespace(dict):<br>
...     def __getitem__(self, key):<br>
...             print "Looking up key '%s'" % key<br>
...             return super(MyNamespace, self).__getitem__(key)<br>
...<br>
>>> namespace = MyNamespace(x=1, y=2, z=3)<br>
>>> namespace['x']<br>
Looking up key 'x'<br>
1<br>
>>> C = new.classobj("C", (object,), namespace)<br>
>>> C.x<br>
1<br>
<br>
Apparently not. It looks like the namespace provided to the class<br>
constructor gets copied when the class is made.<br>
<br>
Interestingly enough, the namespace argument gets modified *before* it<br>
gets copied, which has an unwanted side-effect:<br>
<br>
>>> namespace<br>
{'y': 2, 'x': 1, '__module__': '__main__', 'z': 3, '__doc__': None}<br>
<br>
<br>
Is there any way to install a custom type as a namespace?<br>
<br>
<br>
<br>
--<br>
Steven<br>
<font color="#888888">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></blockquote></div><br>