Skip to content

Commit 03d3e16

Browse files
committed
Declare CachedReadOnlyProperty as generic
It allows type checking of instances and property values.
1 parent ac1598a commit 03d3e16

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

stagpy/_helpers.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22

33
from __future__ import annotations
44
from inspect import getdoc
5-
import typing
5+
from typing import TYPE_CHECKING, Generic, TypeVar
66

77
import matplotlib.pyplot as plt
88

99
from . import conf
1010

11-
if typing.TYPE_CHECKING:
11+
if TYPE_CHECKING:
1212
from typing import Optional, Any, List, Callable
1313
from matplotlib.figure import Figure
1414
from numpy import ndarray
@@ -125,7 +125,11 @@ def find_in_sorted_arr(value: Any, array: ndarray, after=False) -> int:
125125
return ielt
126126

127127

128-
class CachedReadOnlyProperty:
128+
T = TypeVar('T')
129+
V = TypeVar('V')
130+
131+
132+
class CachedReadOnlyProperty(Generic[T, V]):
129133
"""Descriptor implementation of read-only cached properties.
130134
131135
Properties are cached as ``_cropped_{name}`` instance attribute.
@@ -140,13 +144,13 @@ class CachedReadOnlyProperty:
140144
property is read-only instead of being writeable.
141145
"""
142146

143-
def __init__(self, thunk: Callable[[Any], Any]):
147+
def __init__(self, thunk: Callable[[T], V]):
144148
self._thunk = thunk
145149
self._name = thunk.__name__
146150
self._cache_name = f'_cropped_{self._name}'
147151
self.__doc__ = thunk.__doc__
148152

149-
def __get__(self, instance: Any, _) -> Any:
153+
def __get__(self, instance: T, _) -> V:
150154
try:
151155
return getattr(instance, self._cache_name)
152156
except AttributeError:
@@ -155,6 +159,6 @@ def __get__(self, instance: Any, _) -> Any:
155159
setattr(instance, self._cache_name, cached_value)
156160
return cached_value
157161

158-
def __set__(self, instance: Any, _):
162+
def __set__(self, instance: T, _):
159163
raise AttributeError(
160164
f'Cannot set {self._name} property of {instance!r}')

0 commit comments

Comments
 (0)