Typed decorators for classproperty and cached_classproperty.
Python 3 compatible only. No dependencies[1].
uv add typed_classpropertiespath/to/venv/python -m pip install typed_classpropertiesfrom typing import override
from typed_classproperties import classproperty, cached_classproperty
class Foo:
@override
def __init__(self, bar: str) -> None:
self.bar: str = bar
@classproperty
def BAR(cls) -> int:
return 1
assert Foo.BAR == 1
assert Foo(bar="one").BAR == 1
class CachedFoo:
@override
def __init__(self, bar: str) -> None:
self.bar: str = bar
@cached_classproperty
def BAR(cls) -> int:
print("This will be executed only once")
return 1
assert CachedFoo.BAR == 1
assert CachedFoo(bar="bar").FOO == 1This package makes use of some reasonably advanced Python functionality, not supported by all static type checkers. While we will attempt to fix type bugs in this project for alternative type-checkers, our focus is on the following officially supported type checkers[2]:
|
Important
|
Patches to fix bugs in this project for alternative type-checkers are welcome and much appreciated! |
See tests.py for further usage examples and expected behaviour.
uv run --group test -- pytestCredits to Denis Ryzhkov, on Stack Overflow, for the original implementation of the @classproperty decorator:
https://stackoverflow.com/a/13624858/1280629