Custom namespaces

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Aug 2 09:18:53 CEST 2009


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

MyClass = Meta('MyClass', (object,), dict(x=1, y=2))





-- 
Steven



More information about the Python-list mailing list