In 3.9 and 3.10, we were allowed to compose classmethod
and property
like so:
class A:
@classmethod
@property
def x(cls):
return "o hi"
print(A.x)
In 3.11 this was removed, and I am NOT proposing that it comes back.
I’m having trouble finding the bug reports right now, but there were issues with this composition.
I would suggest that most users of classproperties are satisfied for them to be read-only.
You can implement it yourself with a descriptor like so:
from typing import Any, Callable, Generic, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class classproperty(Generic[T, R]):
def __init__(self, func: Callable[[type[T]], R]) -> None:
self.func = func
def __get__(self, obj: Any, cls: type[T]) -> R:
return self.func(cls)
Why is this solution insufficient?
The main issue is that this is not in any way standardized, so the seams will tend to show between various tools.
- How can I explain this descriptor to a tool like Sphinx?
- mypy has an issue about almost this exact usage not working correctly Make classproperty descriptor work · Issue #2563 · python/mypy · GitHub , which seems related (it at least demonstrates the prominence of this use-case)
Would there be a home for a classproperty
descriptor in the stdlib? If so, where?