Declarative properties

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Oct 11 12:51:01 EDT 2007


Artur Siekielski a écrit :
> Hi.
> 
> I would like to have declarative properties in Python, ie. something
> like slots definitions in defclass in Common Lisp. It seems that even
> Java will have it, using a library ( https://bean-properties.dev.java.net/
> ).
> 
> I know about 'property' function

Actually, it's a class.

> in Python, but it's normal usage
> isn't declarative, because I have to code imperatively getters and
> setters:

Indeed. What would be the use of a property (AKA computed attribute) if 
you don't need to do something specific ?

> class Person(object):
>    def __init__(self, name):
>       self._name = name
>    def _get_name(self):
>       return self._name
>    def _set_name(self, new_name):
>       self._name = new_name
>    name = property(_get_name, _set_name)

While it's often seen as demonstration code for a property, it's 
actually totally useless. If all you want to do is to get and set an 
attribute (I mean, without any computation anywhere), then just use an 
attribute - you will always be able to turn it into a property if and 
whene the need arises.

> I would like to have something like that:
> 
> class Person(object):
>    name = property('_name')
> 
> I assume that this causes "generation" of instance field '_name' and
> default getters and setters.

So far, it's a waste of time. That's exactly what you'd get with a plain 
attribute, with far less complexity and overhead.

> And if I would like to customize (g|
> s)etters, I would write them by hand,

Which bring us back to how properties actually work !-)

> or, better, use more declarative
> approach (like @NotNull annotations in Java version).

> I could probably code a solution to my problem with help of wonderful
> introspection functionalities. But I'm looking for a standard and/or
> proven way of doing this. Maybe some PEP is being prepared for this?

I guess you want to have a look at the descriptor protocol - it's what 
makes properties work, and it allow you to write your own custom 'smart 
attributes'. If you want automatic validation/conversion, you could 
write custom descriptors working with the FormEncode package (I started 
such a thing for Elixir, but had no time to finish it so far). It would 
then looks like:

class Person(object):
   name = StringField(empty=False)

   // etc

HTH



More information about the Python-list mailing list