|
| 1 | +"""Backward compatibility for newer/less buggy typing features. |
| 2 | +
|
| 3 | +## Important |
| 4 | +Import from here to avoid introducing a runtime dependency on [`typing_extensions`] |
| 5 | +
|
| 6 | +## Notes |
| 7 | +- `Protocol38` |
| 8 | + - https://github.com/narwhals-dev/narwhals/pull/2064#discussion_r1965921386 |
| 9 | + - https://github.com/narwhals-dev/narwhals/pull/2294#discussion_r2014534830 |
| 10 | +- `TypeVar` defaults |
| 11 | + - https://typing.python.org/en/latest/spec/generics.html#type-parameter-defaults |
| 12 | + - https://peps.python.org/pep-0696/ |
| 13 | +- `@deprecated` |
| 14 | + - https://docs.python.org/3/library/warnings.html#warnings.deprecated |
| 15 | + - https://typing.python.org/en/latest/spec/directives.html#deprecated |
| 16 | + - https://peps.python.org/pep-0702/ |
| 17 | +
|
| 18 | +[`typing_extensions`]: https://github.com/python/typing_extensions |
| 19 | +""" |
| 20 | + |
| 21 | +from __future__ import annotations |
| 22 | + |
| 23 | +# ruff: noqa: ARG001, ANN202, N802 |
| 24 | +import sys |
| 25 | +from typing import TYPE_CHECKING |
| 26 | +from typing import Any |
| 27 | + |
| 28 | +if TYPE_CHECKING: |
| 29 | + from typing import Callable |
| 30 | + from typing import Protocol as Protocol38 |
| 31 | + |
| 32 | + if sys.version_info >= (3, 13): |
| 33 | + from typing import TypeVar |
| 34 | + from warnings import deprecated |
| 35 | + else: |
| 36 | + from typing_extensions import TypeVar |
| 37 | + from typing_extensions import deprecated |
| 38 | + |
| 39 | + _Fn = TypeVar("_Fn", bound=Callable[..., Any]) |
| 40 | + |
| 41 | + |
| 42 | +else: # pragma: no cover |
| 43 | + if sys.version_info >= (3, 13): |
| 44 | + from typing import TypeVar |
| 45 | + from warnings import deprecated |
| 46 | + else: |
| 47 | + from typing import TypeVar as _TypeVar |
| 48 | + |
| 49 | + def TypeVar( |
| 50 | + name: str, |
| 51 | + *constraints: Any, |
| 52 | + bound: Any | None = None, |
| 53 | + covariant: bool = False, |
| 54 | + contravariant: bool = False, |
| 55 | + **kwds: Any, |
| 56 | + ): |
| 57 | + return _TypeVar( |
| 58 | + name, |
| 59 | + *constraints, |
| 60 | + bound=bound, |
| 61 | + covariant=covariant, |
| 62 | + contravariant=contravariant, |
| 63 | + ) |
| 64 | + |
| 65 | + def deprecated(message: str, /) -> Callable[[_Fn], _Fn]: |
| 66 | + def wrapper(func: _Fn, /) -> _Fn: |
| 67 | + return func |
| 68 | + |
| 69 | + return wrapper |
| 70 | + |
| 71 | + # TODO @dangotbanned: Remove after dropping `3.8` (#2084) |
| 72 | + # - https://github.com/narwhals-dev/narwhals/pull/2064#discussion_r1965921386 |
| 73 | + if sys.version_info >= (3, 9): |
| 74 | + from typing import Protocol as Protocol38 |
| 75 | + else: |
| 76 | + from typing import Generic as Protocol38 |
| 77 | + |
| 78 | + |
| 79 | +__all__ = ["Protocol38", "TypeVar", "deprecated"] |
0 commit comments