properties + types, implementing meta-class desciptors elegantly?

Michael Hudson mwh at python.net
Mon Jul 21 08:30:25 EDT 2003


Michael Hudson <mwh at python.net> writes:

> "Mike C. Fletcher" <mcfletch at rogers.com> 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)
                break
        else:
            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 :-)

Cheers,
mwh

-- 
3. Syntactic sugar causes cancer of the semicolon.
  -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html




More information about the Python-list mailing list