clp2 at rebertia.com
Sun Aug 2 09:31:05 CEST 2009
On Sun, Aug 2, 2009 at 12:18 AM, Steven
D'Aprano<steve at remove-this-cybersource.com.au> wrote:
> On Sat, 01 Aug 2009 21:46:35 -0700, Chris Rebert wrote:
>>> Is there any way to install a custom type as a namespace?
>> For classes/objects, yes, using metaclasses. See the __prepare__()
>> method in PEP 3115: http://www.python.org/dev/peps/pep-3115/
> Looks good, but that's Python 3 only, yes?
> At least, I can't get the metaclass to change the __dict__ in Python 2.6.
> There's obviously no __prepare__ before 3.0, but I tried the following,
> and still __dict__ ends up as a regular dict. Am I missing something?
> class VerboseDict(dict):
> def __getitem__(self, item):
> print ("Looking up key '%s'..." % item)
> return super(VerboseDict, self).__getitem__(item)
> class Meta(type):
> def __new__(cls, name, bases, namespace):
> namespace = VerboseDict(namespace)
> obj = super(Meta, cls).__new__(cls, name, bases, namespace)
> return obj
I would /guess/ that type.__new__() is internally doing the equivalent
of dict(namespace). Hence why the addition of __prepare__() was
necessary; it's probably impossible to accomplish what you want in
earlier Python versions.
More information about the Python-list