[Tutor] classproperty for Python 2.7 (read-only enough)
Steven D'Aprano
steve at pearwood.info
Wed Apr 19 05:16:30 EDT 2017
On Wed, Apr 19, 2017 at 09:28:26AM +0200, Thomas Güttler wrote:
[code for a classproperty]
> Nice, if it is that simple.
>
> Is there a reason why this is not in the standard library?
I haven't had a chance to test Peter's classproperty code yet, but I
don't expect it to be that simple. People have asked for it before, and
even Guido himself (the inventor of Python) has agreed that if it
existed he'd use it, but the proposals have (so far) always stumbled on
two factors:
- there are not a lot of uses for classproperty that ordinary property
isn't "good enough" for;
- its hard to get classproperty to work right.
The *easy* part is to do something like this:
class Spam(object):
@classproperty
def x(cls):
return "some value"
Now you can say:
Spam.x
and it will return "some value". BUT if you say:
Spam.x = "hello world"
the class property doesn't run, and Python just overrides x with the new
value, and you lose the class property and get just a regular attribute.
That's bad.
There is a solution to that: use a custom metaclass. And yes, that is
not just advanced, but Black Magic and Voodoo advanced. But if you do
it, you can solve the above problem.
However, the metaclass solution creates a *new* problem. We'd like this
to work too:
obj = Spam()
obj.x # should call the classproperty and return "some value"
but with the metaclass solution, that doesn't work.
As I said, I haven't had a chance to try Peter's code, so it's possible
that he's solved all these problems. I'm judging by previous
discussions.
On the bug tracker there's currently a request for classproperty, but
its languishing:
https://bugs.python.org/issue24941
See Nick Coghlan's comments in particular:
https://mail.python.org/pipermail/python-ideas/2011-January/008959.html
Here's a previous request that was closed for lack of progress and
interest:
https://bugs.python.org/issue23586
Here's Guido expressing some interest:
https://mail.python.org/pipermail/python-ideas/2011-January/008955.html
--
Steve
More information about the Tutor
mailing list