[Tutor] classproperty for Python 2.7 (read-only enough)

Mats Wichmann mats at wichmann.us
Tue Apr 18 09:47:27 EDT 2017


On 04/18/2017 04:00 AM, Thomas Güttler wrote:
> I would like to have read-only class properties in Python.
> 
> I found this
> http://stackoverflow.com/questions/128573/using-property-on-classmethods
> But there are a lot of discussions of things which I don't understand.
> 
> I want to be a user of class properties, not an implementer of the details.
> 
> I found this: https://pypi.python.org/pypi/classproperty
> 
> But above release is more then ten years old. I am unsure if it's dead
> or mature.
> 
> I am using Python 2.7 and attribute getters would be enough, no
> attribute setter is needed.
> 
> My use case is configuration, not fancy algorithms or loops.
> 
> Regards,
>   Thomas Güttler
> 

Not clear if you're asking for something more than the standard Python
properties.  The discussion you mention does go into additional
discussion which describes techniques for applying this to a class
attribute. In other words, is this quote a problem for you?

"The get method [of a property] won't be called when the property is
accessed as a class attribute (C.x) instead of as an instance attribute
(C().x). "

If applying to instance attributes is fine for your case, then the
property() call or the related decorators should do the trick, as in:

    def get_temperature(self):
        return self._temperature

    def set_temperature(self, value):
        self._temperature = value

    temperature = property(get_temperature,set_temperature)

or, as is probably preferred:

    @property
    def temperature(self):
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        self._temperature = value

(obviously both a getter and setter)

Note it's Python convention to use an underscore-prefixed variable name
to indicate it is "private", and you often see a backing store for the
property written like I did above, but nothing in Python enforces this
privacy, someone could fiddle directly with instance._temperature

Also ask yourself whether you really _need_ a property here?  Or would a
public data member be sufficient.  (Just asking, have no idea what's
inside your use case)



More information about the Tutor mailing list