Skip to content
 
 

Repository files navigation

typed_classproperties

Pydowndoc PyPI Version Python Version Tests Status mypy Status pre-commit Status ruff uv

Typed decorators for classproperty and cached_classproperty.

Python 3 compatible only. No dependencies[1].

Installation

This package is hosted on PyPI and can be installed using uv or pip.

uv add typed_classproperties
path/to/venv/python -m pip install typed_classproperties

Example Usage

from 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 == 1

Supported Type-Checkers

This package makes use of some reasonably advanced Python functionality that could be considered a hack. The appropriate solution to correctly annotate the types matching the runtime behaviour of classproperties is explained in PEP767. This PEP, however, is still in draft and not yet accepted; therefore, not all type checkers are supported.

While we will attempt to fix type annotation 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!

Tests

See tests.py for further usage examples and expected behaviour.

To run tests
uv run --group test -- pytest

Credits

Credits to Denis Ryzhkov, on Stack Overflow, for the original implementation of the @classproperty decorator: https://stackoverflow.com/a/13624858/1280629


1. The library typing_extensions is required when running with a Python version less than 3.12
2. The list of officially supported type checkers is subject to change between any minor version release
3. Support for ty is capped to below 0.0.60, which began to find type-errors with the hacks used in this project

About

Typed Python decorators for classproperty and cached_classproperty

Topics

Resources

Stars

Watchers

Forks

Releases

Contributors

Languages