user-supplied locals dict for function execution?
Ziga Seilnacht
ziga.seilnacht at gmail.com
Tue Mar 21 11:13:05 EST 2006
Lonnie Princehouse wrote:
> Occaisionally, the first two lines of The Zen of Python conflict with
> one another.
>
> An API I'm working on involves a custom namespace implementation using
> dictionaries, and I want a pretty syntax for initializing the custom
> namespaces. The fact that these namespaces are implemented as
> dictionaries is an implementation detail, and I don't want the users to
> access them directly. I find the "implicit update" syntax to be much
> cleaner:
>
This can be easier achieved with a custom metaclass:
>>> class MetaNamespace(type):
... def __new__(metaclass, name, bases, dict):
... try:
... Namespace
... except NameError:
... return type.__new__(metaclass, name, bases, dict)
... dict.pop('__module__', None)
... return dict
...
>>> class Namespace(object):
... __metaclass__ = MetaNamespace
...
Now whenever you want to create your dictionary you simply
declare a class that inherits from Namespace:
>>> class MyNamespace(Namespace):
... x = 5
... y = 'spam'
... z = 'eggs'
...
>>> print sorted(MyNamespace.items())
[('x', 5), ('y', 'spam'), ('z', 'eggs')]
Ziga
More information about the Python-list
mailing list