Are decorators really that different from metaclasses...

Anthony Baxter anthonybaxter at gmail.com
Thu Aug 26 11:25:01 EDT 2004


On Thu, 26 Aug 2004 11:15:46 -0400, Paul Morrow <pm_mon at yahoo.com> wrote:
> __getitem__ is most certainly magical!  Defining it 'declares'
> (implicitly, but we'll ignore that governing zen rule for the moment)
> that instances of the containing class have dictionary semantics (that
> they can be used, in some degree, like dictionaries).  That's magic.
> That's meta.  That's profoundly deeper than anything defining getMonkey
> does.

What? There is *nothing* that __getitem__ "declares". __getitem__ is
used by the interpreter. When do make a call like:

someobj[key]

the interpreter turns that into 

someobj.__getitem__(key)

That's all. I can make an object that acts like a dictionary _without_
using a __getitem__, watch:

class Foo:
    def __init__(self):
        self.d = dict(ape=False,spidermonkey=True)

    def getMonkey(self, key):
        return self.d[key]

    def __getattr__(self, name):
        if name == "__getitem__":
            return self.getMonkey
        else:
            raise AttributeError, name

f = Foo()
print f['ape']
print f['spidermonkey']



More information about the Python-list mailing list