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

Guido van Rossum guido at python.org
Tue Oct 18 05:46:47 CEST 2005

> > > IMO, there's not enough advantage in having the property() call before
> > > the functions than after.

> > Maybe you didn't see the use case that Greg had in mind? He wants to
> > be able to override the getter and/or setter in a subclass, without
> > changing the docstring or having to repeat the property() call. That
> > requires us to do a late binding lookup based on a string.

> True, I missed that use case.  But can't you already support
> override-ability just by refactoring the getter and setter into separate
> methods?  IOW, the getter and setter isn't overridden, but they call
> other methods that implement the core functionality and that /are/
> overridden.  Okay, that means a few extra methods per property, but that
> still doesn't seem too bad.
> > If you can think of a solution that looks better than mine, you're a genius.
> Oh, I know that's not the case, but it's such a tempting challenge, I'll
> try anyway :).

Nice try. I guess it's similar to this, which is a bit more concise
and doesn't require as many underscores:

class B:
    def get_x(self): return self._x
    def set_x(self, x): self._x = x
    x = property(lambda self: self.get_x(), lambda self, x: self.set_x(x))

But I still like the version with strings better:

    x = property('get_x', 'set_x')

This trades two lambdas for two pairs of string quotes; a good deal IMO!

Now, if I were to follow Paul Graham's recommendations strictly
(http://www.paulgraham.com/diff.html), point 7 saysthat Python should
have a symbol type. I've always maintained that this is unnecessary
and that we can just as well use regular strings. This makes it easy
to constructs names on the fly that you pass to getattr() and
setattr() using standard string operations. Suppose the symbol type
were written as \foo (meaning a quoted reference to the identifier
'foo'). Then the above could be written like this:

    x = property(\get_x, \set_x)

But I'm not sure this buys us anything, so I still believe that using
'set_x' and 'get_x' is just fine here. Greg Ewing, whose taste in
language features is hard to beat, seems to agree.

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list