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

Guido van Rossum guido at python.org
Mon Oct 17 05:06:23 CEST 2005


[Guido]
> > Nick, and everybody else trying to find a "solution" for this
> > "problem", please don't.

[Greg Ewing]
> Denying that there's a problem isn't going to make it
> go away. Many people, including me, have the feeling that
> the standard way of defining properties at the moment leaves
> something to be desired, for all the same reasons that have
> led to @-decorators.

My challenge to many people, including you, is to make that feeling
more concrete. Sometimes when you have such a feeling it just means
you haven't drunk the kool-aid yet. :)

With decorators there was a concrete issue: the modifier trailed after
the function body, in a real sense "hiding" from the reader. I don't
see such an issue with properties. Certainly the proposed solutions so
far are worse than the problem.

> However, I agree that trying to keep the accessor method
> names out of the class namespace isn't necessary, and may
> not even be desirable. The way I'm defining properties in
> PyGUI at the moment looks like this:
>
>    class C:
>
>      foo = overridable_property('foo', "The foo property")
>
>      def get_foo(self):
>        ...
>
>      def set_foo(self, x):
>        ...
>
> This has the advantage that the accessor methods can be
> overridden in subclasses with the expected effect. This
> is particularly important in PyGUI, where I have a generic
> class definition which establishes the valid properties
> and their docstrings, and implementation subclasses for
> different platforms which supply the accessor methods.

But since you define the API, are you sure that you need properties at
all? Maybe the users would be happy to write widget.get_foo() and
widget.set_foo(x) instead of widget.foo or widget.foo = x?

> The only wart is the necessity of mentioning the property
> name twice, once on the lhs and once as an argument.
> I haven't thought of a good solution to that, yet.

To which Tim Delaney responded, "have a look at my response here:"
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/408713

I looked at that, and now I believe it's actually *better* to mention
the property name twice, at least compared to Tim' s approach. Looking
at that version, I think it's obscuring the semantics; it (ab)uses the
fact that a function's name is accessible through its __name__
attribute. But (unlike Greg's version) it breaks down when one of the
arguments is not a plain function. This makes it brittle in the
context of renaming operations, e.g.:

    getx = lambda self: 42
    def sety(self, value): self._y = value
    setx = sety
    x = LateBindingProperty(getx, setx)

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


More information about the Python-Dev mailing list