|
10 | 10 | from contextlib import contextmanager
|
11 | 11 | from inspect import Parameter
|
12 | 12 | from inspect import signature
|
| 13 | +from typing import Callable |
| 14 | +from typing import Generic |
| 15 | +from typing import Optional |
13 | 16 | from typing import overload
|
| 17 | +from typing import TypeVar |
14 | 18 |
|
15 | 19 | import attr
|
16 | 20 | import py
|
|
20 | 24 | from _pytest.outcomes import fail
|
21 | 25 | from _pytest.outcomes import TEST_OUTCOME
|
22 | 26 |
|
| 27 | +if False: # TYPE_CHECKING |
| 28 | + from typing import Type # noqa: F401 (used in type string) |
| 29 | + |
| 30 | + |
| 31 | +_T = TypeVar("_T") |
| 32 | +_S = TypeVar("_S") |
| 33 | + |
23 | 34 |
|
24 | 35 | NOTSET = object()
|
25 | 36 |
|
@@ -374,3 +385,33 @@ def overload(f): # noqa: F811
|
374 | 385 | ATTRS_EQ_FIELD = "eq"
|
375 | 386 | else:
|
376 | 387 | ATTRS_EQ_FIELD = "cmp"
|
| 388 | + |
| 389 | + |
| 390 | +if sys.version_info >= (3, 8): |
| 391 | + # TODO: Remove type ignore on next mypy update. |
| 392 | + # https://github.com/python/typeshed/commit/add0b5e930a1db16560fde45a3b710eefc625709 |
| 393 | + from functools import cached_property # type: ignore |
| 394 | +else: |
| 395 | + |
| 396 | + class cached_property(Generic[_S, _T]): |
| 397 | + __slots__ = ("func", "__doc__") |
| 398 | + |
| 399 | + def __init__(self, func: Callable[[_S], _T]) -> None: |
| 400 | + self.func = func |
| 401 | + self.__doc__ = func.__doc__ |
| 402 | + |
| 403 | + @overload |
| 404 | + def __get__( |
| 405 | + self, instance: None, owner: Optional["Type[_S]"] = ... |
| 406 | + ) -> "cached_property[_S, _T]": |
| 407 | + raise NotImplementedError() |
| 408 | + |
| 409 | + @overload # noqa: F811 |
| 410 | + def __get__(self, instance: _S, owner: Optional["Type[_S]"] = ...) -> _T: |
| 411 | + raise NotImplementedError() |
| 412 | + |
| 413 | + def __get__(self, instance, owner=None): # noqa: F811 |
| 414 | + if instance is None: |
| 415 | + return self |
| 416 | + value = instance.__dict__[self.func.__name__] = self.func(instance) |
| 417 | + return value |
0 commit comments