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

Thomas Güttler guettliml at thomas-guettler.de
Wed Apr 19 03:28:26 EDT 2017


Am 18.04.2017 um 13:17 schrieb Peter Otten:
> 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.
>
> Like this?
>
> $ cat classproperty.py
> class classproperty(object):
>     def __init__(self, fget):
>         self.fget = fget
>     def __get__(self, inst, cls):
>         return self.fget(cls)
>
>
> class Foo(object):
>     FOO = 42
>     @classproperty
>     def foo(cls):
>         return cls.FOO
>
> print "Foo.foo =", Foo.foo
> print "Foo().foo =", Foo().foo
> $ python2 classproperty.py
> Foo.foo = 42
> Foo().foo = 42

Nice, if it is that simple.

Is there a reason why this is not in the standard library?

Regards,
   Thomas Güttler



-- 
Thomas Guettler http://www.thomas-guettler.de/


More information about the Tutor mailing list