Custom namespaces

Red Forks redforks at gmail.com
Sun Aug 2 03:18:58 CEST 2009


On Sun, Aug 2, 2009 at 9:06 AM, Steven D'Aprano <
steve at remove-this-cybersource.com.au> wrote:

> I was playing around with a custom mapping type, and I wanted to use it
> as a namespace, so I tried to use it as my module __dict__:
>
> >>> import __main__
> >>> __main__.__dict__ = MyNamespace()
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> TypeError: readonly attribute
>
> Why is __dict__ made read-only?

to protect module type? Use .update() method:
__main.__.__dict__.update(MyNamespace())
You can create your own Module instance:
from types import ModuleType
m = ModuleType('modulename')
and make a sub class of ModuleType is also OK

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


More information about the Python-list mailing list