properties + types, implementing meta-class desciptors elegantly?

Michael Hudson mwh at
Mon Jul 21 14:30:25 CEST 2003

Michael Hudson <mwh at> writes:

> "Mike C. Fletcher" <mcfletch at> writes:
> > So, does anyone have a pattern which allows setting an attribute on
> > a class which doesn't go through the setattr machinery (i.e. can be
> > used within a descriptor)?
> No.  Fun problem to think about, though :-)

Actually, that was a lie.  Check this horror out:

class MetaProp(object):
    def __init__(self, val):
        self.val = val
    def __get__(self, ob, cls=None):
        for k in ob.__class__.__dict__:
            if ob.__class__.__dict__[k] is self:
                delattr(ob.__class__, k)
            raise Exception, 'not found'
        setattr(ob, k, self.val + 1)
        setattr(ob.__class__, k, self)
        return self.val

class Meta(type):
    p = MetaProp(1)

class C:
    __metaclass__ = Meta

print C.__dict__.keys()
print C.p
print C.__dict__.keys()
print C.p

I'm quite proud of this one :-)


3. Syntactic sugar causes cancer of the semicolon.
  -- Alan Perlis,

More information about the Python-list mailing list