[Python-Dev] Definining properties - a use case for class decorators?

Michael Urman murman at gmail.com
Mon Oct 17 09:09:12 CEST 2005

On 10/16/05, Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> On and off, I've been looking for an elegant way to handle properties using
> decorators.

Why use decorators when a metaclass will already do the trick, and
save you a line? This doesn't necessarily get around Antoine's
complaint that it looks like self refers to the wrong type, but I'm
not convinced anyone would be confused.

class MetaProperty(type):
    def __new__(cls, name, bases, dct):
        if bases[0] is object: # allow us to create class Property
            return type.__new__(cls, name, bases, dct)
        return property(dct.get('get'), dct.get('set'),
                dct.get('delete'), dct.get('__doc__'))

    def __init__(cls, name, bases, dct):
        if bases[0] is object:
            return type.__init__(cls, name, bases, dct)

class Property(object):
    __metaclass__ = MetaProperty

class Test(object):
    class foo(Property):
        """The foo property"""
        def get(self): return self._foo
        def set(self, val): self._foo = val
        def delete(self): del self._foo

test = Test()
test.foo = 'Yay!'
assert test._foo == 'Yay!'

More information about the Python-Dev mailing list