| 1 |
import abc |
| 2 |
import collections |
| 3 |
import collections.abc |
| 4 |
import contextlib |
| 5 |
import functools |
| 6 |
import inspect |
| 7 |
import operator |
| 8 |
import sys |
| 9 |
import types as _types |
| 10 |
import typing |
| 11 |
import warnings |
| 12 |
|
| 13 |
__all__ = [ |
| 14 |
# Super-special typing primitives. |
| 15 |
'Any', |
| 16 |
'ClassVar', |
| 17 |
'Concatenate', |
| 18 |
'Final', |
| 19 |
'LiteralString', |
| 20 |
'ParamSpec', |
| 21 |
'ParamSpecArgs', |
| 22 |
'ParamSpecKwargs', |
| 23 |
'Self', |
| 24 |
'Type', |
| 25 |
'TypeVar', |
| 26 |
'TypeVarTuple', |
| 27 |
'Unpack', |
| 28 |
|
| 29 |
# ABCs (from collections.abc). |
| 30 |
'Awaitable', |
| 31 |
'AsyncIterator', |
| 32 |
'AsyncIterable', |
| 33 |
'Coroutine', |
| 34 |
'AsyncGenerator', |
| 35 |
'AsyncContextManager', |
| 36 |
'Buffer', |
| 37 |
'ChainMap', |
| 38 |
|
| 39 |
# Concrete collection types. |
| 40 |
'ContextManager', |
| 41 |
'Counter', |
| 42 |
'Deque', |
| 43 |
'DefaultDict', |
| 44 |
'NamedTuple', |
| 45 |
'OrderedDict', |
| 46 |
'TypedDict', |
| 47 |
|
| 48 |
# Structural checks, a.k.a. protocols. |
| 49 |
'SupportsAbs', |
| 50 |
'SupportsBytes', |
| 51 |
'SupportsComplex', |
| 52 |
'SupportsFloat', |
| 53 |
'SupportsIndex', |
| 54 |
'SupportsInt', |
| 55 |
'SupportsRound', |
| 56 |
|
| 57 |
# One-off things. |
| 58 |
'Annotated', |
| 59 |
'assert_never', |
| 60 |
'assert_type', |
| 61 |
'clear_overloads', |
| 62 |
'dataclass_transform', |
| 63 |
'deprecated', |
| 64 |
'Doc', |
| 65 |
'get_overloads', |
| 66 |
'final', |
| 67 |
'get_args', |
| 68 |
'get_origin', |
| 69 |
'get_original_bases', |
| 70 |
'get_protocol_members', |
| 71 |
'get_type_hints', |
| 72 |
'IntVar', |
| 73 |
'is_protocol', |
| 74 |
'is_typeddict', |
| 75 |
'Literal', |
| 76 |
'NewType', |
| 77 |
'overload', |
| 78 |
'override', |
| 79 |
'Protocol', |
| 80 |
'reveal_type', |
| 81 |
'runtime', |
| 82 |
'runtime_checkable', |
| 83 |
'Text', |
| 84 |
'TypeAlias', |
| 85 |
'TypeAliasType', |
| 86 |
'TypeGuard', |
| 87 |
'TypeIs', |
| 88 |
'TYPE_CHECKING', |
| 89 |
'Never', |
| 90 |
'NoReturn', |
| 91 |
'ReadOnly', |
| 92 |
'Required', |
| 93 |
'NotRequired', |
| 94 |
|
| 95 |
# Pure aliases, have always been in typing |
| 96 |
'AbstractSet', |
| 97 |
'AnyStr', |
| 98 |
'BinaryIO', |
| 99 |
'Callable', |
| 100 |
'Collection', |
| 101 |
'Container', |
| 102 |
'Dict', |
| 103 |
'ForwardRef', |
| 104 |
'FrozenSet', |
| 105 |
'Generator', |
| 106 |
'Generic', |
| 107 |
'Hashable', |
| 108 |
'IO', |
| 109 |
'ItemsView', |
| 110 |
'Iterable', |
| 111 |
'Iterator', |
| 112 |
'KeysView', |
| 113 |
'List', |
| 114 |
'Mapping', |
| 115 |
'MappingView', |
| 116 |
'Match', |
| 117 |
'MutableMapping', |
| 118 |
'MutableSequence', |
| 119 |
'MutableSet', |
| 120 |
'NoDefault', |
| 121 |
'Optional', |
| 122 |
'Pattern', |
| 123 |
'Reversible', |
| 124 |
'Sequence', |
| 125 |
'Set', |
| 126 |
'Sized', |
| 127 |
'TextIO', |
| 128 |
'Tuple', |
| 129 |
'Union', |
| 130 |
'ValuesView', |
| 131 |
'cast', |
| 132 |
'no_type_check', |
| 133 |
'no_type_check_decorator', |
| 134 |
] |
| 135 |
|
| 136 |
# for backward compatibility |
| 137 |
PEP_560 = True |
| 138 |
GenericMeta = type |
| 139 |
_PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta") |
| 140 |
|
| 141 |
# The functions below are modified copies of typing internal helpers. |
| 142 |
# They are needed by _ProtocolMeta and they provide support for PEP 646. |
| 143 |
|
| 144 |
|
| 145 |
class _Sentinel: |
| 146 |
def __repr__(self): |
| 147 |
return "<sentinel>" |
| 148 |
|
| 149 |
|
| 150 |
_marker = _Sentinel() |
| 151 |
|
| 152 |
|
| 153 |
if sys.version_info >= (3, 10): |
| 154 |
def _should_collect_from_parameters(t): |
| 155 |
return isinstance( |
| 156 |
t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) |
| 157 |
) |
| 158 |
elif sys.version_info >= (3, 9): |
| 159 |
def _should_collect_from_parameters(t): |
| 160 |
return isinstance(t, (typing._GenericAlias, _types.GenericAlias)) |
| 161 |
else: |
| 162 |
def _should_collect_from_parameters(t): |
| 163 |
return isinstance(t, typing._GenericAlias) and not t._special |
| 164 |
|
| 165 |
|
| 166 |
NoReturn = typing.NoReturn |
| 167 |
|
| 168 |
# Some unconstrained type variables. These are used by the container types. |
| 169 |
# (These are not for export.) |
| 170 |
T = typing.TypeVar('T') # Any type. |
| 171 |
KT = typing.TypeVar('KT') # Key type. |
| 172 |
VT = typing.TypeVar('VT') # Value type. |
| 173 |
T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. |
| 174 |
T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. |
| 175 |
|
| 176 |
|
| 177 |
if sys.version_info >= (3, 11): |
| 178 |
from typing import Any |
| 179 |
else: |
| 180 |
|
| 181 |
class _AnyMeta(type): |
| 182 |
def __instancecheck__(self, obj): |
| 183 |
if self is Any: |
| 184 |
raise TypeError("typing_extensions.Any cannot be used with isinstance()") |
| 185 |
return super().__instancecheck__(obj) |
| 186 |
|
| 187 |
def __repr__(self): |
| 188 |
if self is Any: |
| 189 |
return "typing_extensions.Any" |
| 190 |
return super().__repr__() |
| 191 |
|
| 192 |
class Any(metaclass=_AnyMeta): |
| 193 |
"""Special type indicating an unconstrained type. |
| 194 |
- Any is compatible with every type. |
| 195 |
- Any assumed to have all methods. |
| 196 |
- All values assumed to be instances of Any. |
| 197 |
Note that all the above statements are true from the point of view of |
| 198 |
static type checkers. At runtime, Any should not be used with instance |
| 199 |
checks. |
| 200 |
""" |
| 201 |
def __new__(cls, *args, **kwargs): |
| 202 |
if cls is Any: |
| 203 |
raise TypeError("Any cannot be instantiated") |
| 204 |
return super().__new__(cls, *args, **kwargs) |
| 205 |
|
| 206 |
|
| 207 |
ClassVar = typing.ClassVar |
| 208 |
|
| 209 |
|
| 210 |
class _ExtensionsSpecialForm(typing._SpecialForm, _root=True): |
| 211 |
def __repr__(self): |
| 212 |
return 'typing_extensions.' + self._name |
| 213 |
|
| 214 |
|
| 215 |
Final = typing.Final |
| 216 |
|
| 217 |
if sys.version_info >= (3, 11): |
| 218 |
final = typing.final |
| 219 |
else: |
| 220 |
# @final exists in 3.8+, but we backport it for all versions |
| 221 |
# before 3.11 to keep support for the __final__ attribute. |
| 222 |
# See https://bugs.python.org/issue46342 |
| 223 |
def final(f): |
| 224 |
"""This decorator can be used to indicate to type checkers that |
| 225 |
the decorated method cannot be overridden, and decorated class |
| 226 |
cannot be subclassed. For example: |
| 227 |
|
| 228 |
class Base: |
| 229 |
@final |
| 230 |
def done(self) -> None: |
| 231 |
... |
| 232 |
class Sub(Base): |
| 233 |
def done(self) -> None: # Error reported by type checker |
| 234 |
... |
| 235 |
@final |
| 236 |
class Leaf: |
| 237 |
... |
| 238 |
class Other(Leaf): # Error reported by type checker |
| 239 |
... |
| 240 |
|
| 241 |
There is no runtime checking of these properties. The decorator |
| 242 |
sets the ``__final__`` attribute to ``True`` on the decorated object |
| 243 |
to allow runtime introspection. |
| 244 |
""" |
| 245 |
try: |
| 246 |
f.__final__ = True |
| 247 |
except (AttributeError, TypeError): |
| 248 |
# Skip the attribute silently if it is not writable. |
| 249 |
# AttributeError happens if the object has __slots__ or a |
| 250 |
# read-only property, TypeError if it's a builtin class. |
| 251 |
pass |
| 252 |
return f |
| 253 |
|
| 254 |
|
| 255 |
def IntVar(name): |
| 256 |
return typing.TypeVar(name) |
| 257 |
|
| 258 |
|
| 259 |
# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8 |
| 260 |
if sys.version_info >= (3, 10, 1): |
| 261 |
Literal = typing.Literal |
| 262 |
else: |
| 263 |
def _flatten_literal_params(parameters): |
| 264 |
"""An internal helper for Literal creation: flatten Literals among parameters""" |
| 265 |
params = [] |
| 266 |
for p in parameters: |
| 267 |
if isinstance(p, _LiteralGenericAlias): |
| 268 |
params.extend(p.__args__) |
| 269 |
else: |
| 270 |
params.append(p) |
| 271 |
return tuple(params) |
| 272 |
|
| 273 |
def _value_and_type_iter(params): |
| 274 |
for p in params: |
| 275 |
yield p, type(p) |
| 276 |
|
| 277 |
class _LiteralGenericAlias(typing._GenericAlias, _root=True): |
| 278 |
def __eq__(self, other): |
| 279 |
if not isinstance(other, _LiteralGenericAlias): |
| 280 |
return NotImplemented |
| 281 |
these_args_deduped = set(_value_and_type_iter(self.__args__)) |
| 282 |
other_args_deduped = set(_value_and_type_iter(other.__args__)) |
| 283 |
return these_args_deduped == other_args_deduped |
| 284 |
|
| 285 |
def __hash__(self): |
| 286 |
return hash(frozenset(_value_and_type_iter(self.__args__))) |
| 287 |
|
| 288 |
class _LiteralForm(_ExtensionsSpecialForm, _root=True): |
| 289 |
def __init__(self, doc: str): |
| 290 |
self._name = 'Literal' |
| 291 |
self._doc = self.__doc__ = doc |
| 292 |
|
| 293 |
def __getitem__(self, parameters): |
| 294 |
if not isinstance(parameters, tuple): |
| 295 |
parameters = (parameters,) |
| 296 |
|
| 297 |
parameters = _flatten_literal_params(parameters) |
| 298 |
|
| 299 |
val_type_pairs = list(_value_and_type_iter(parameters)) |
| 300 |
try: |
| 301 |
deduped_pairs = set(val_type_pairs) |
| 302 |
except TypeError: |
| 303 |
# unhashable parameters |
| 304 |
pass |
| 305 |
else: |
| 306 |
# similar logic to typing._deduplicate on Python 3.9+ |
| 307 |
if len(deduped_pairs) < len(val_type_pairs): |
| 308 |
new_parameters = [] |
| 309 |
for pair in val_type_pairs: |
| 310 |
if pair in deduped_pairs: |
| 311 |
new_parameters.append(pair[0]) |
| 312 |
deduped_pairs.remove(pair) |
| 313 |
assert not deduped_pairs, deduped_pairs |
| 314 |
parameters = tuple(new_parameters) |
| 315 |
|
| 316 |
return _LiteralGenericAlias(self, parameters) |
| 317 |
|
| 318 |
Literal = _LiteralForm(doc="""\ |
| 319 |
A type that can be used to indicate to type checkers |
| 320 |
that the corresponding value has a value literally equivalent |
| 321 |
to the provided parameter. For example: |
| 322 |
|
| 323 |
var: Literal[4] = 4 |
| 324 |
|
| 325 |
The type checker understands that 'var' is literally equal to |
| 326 |
the value 4 and no other value. |
| 327 |
|
| 328 |
Literal[...] cannot be subclassed. There is no runtime |
| 329 |
checking verifying that the parameter is actually a value |
| 330 |
instead of a type.""") |
| 331 |
|
| 332 |
|
| 333 |
_overload_dummy = typing._overload_dummy |
| 334 |
|
| 335 |
|
| 336 |
if hasattr(typing, "get_overloads"): # 3.11+ |
| 337 |
overload = typing.overload |
| 338 |
get_overloads = typing.get_overloads |
| 339 |
clear_overloads = typing.clear_overloads |
| 340 |
else: |
| 341 |
# {module: {qualname: {firstlineno: func}}} |
| 342 |
_overload_registry = collections.defaultdict( |
| 343 |
functools.partial(collections.defaultdict, dict) |
| 344 |
) |
| 345 |
|
| 346 |
def overload(func): |
| 347 |
"""Decorator for overloaded functions/methods. |
| 348 |
|
| 349 |
In a stub file, place two or more stub definitions for the same |
| 350 |
function in a row, each decorated with @overload. For example: |
| 351 |
|
| 352 |
@overload |
| 353 |
def utf8(value: None) -> None: ... |
| 354 |
@overload |
| 355 |
def utf8(value: bytes) -> bytes: ... |
| 356 |
@overload |
| 357 |
def utf8(value: str) -> bytes: ... |
| 358 |
|
| 359 |
In a non-stub file (i.e. a regular .py file), do the same but |
| 360 |
follow it with an implementation. The implementation should *not* |
| 361 |
be decorated with @overload. For example: |
| 362 |
|
| 363 |
@overload |
| 364 |
def utf8(value: None) -> None: ... |
| 365 |
@overload |
| 366 |
def utf8(value: bytes) -> bytes: ... |
| 367 |
@overload |
| 368 |
def utf8(value: str) -> bytes: ... |
| 369 |
def utf8(value): |
| 370 |
# implementation goes here |
| 371 |
|
| 372 |
The overloads for a function can be retrieved at runtime using the |
| 373 |
get_overloads() function. |
| 374 |
""" |
| 375 |
# classmethod and staticmethod |
| 376 |
f = getattr(func, "__func__", func) |
| 377 |
try: |
| 378 |
_overload_registry[f.__module__][f.__qualname__][ |
| 379 |
f.__code__.co_firstlineno |
| 380 |
] = func |
| 381 |
except AttributeError: |
| 382 |
# Not a normal function; ignore. |
| 383 |
pass |
| 384 |
return _overload_dummy |
| 385 |
|
| 386 |
def get_overloads(func): |
| 387 |
"""Return all defined overloads for *func* as a sequence.""" |
| 388 |
# classmethod and staticmethod |
| 389 |
f = getattr(func, "__func__", func) |
| 390 |
if f.__module__ not in _overload_registry: |
| 391 |
return [] |
| 392 |
mod_dict = _overload_registry[f.__module__] |
| 393 |
if f.__qualname__ not in mod_dict: |
| 394 |
return [] |
| 395 |
return list(mod_dict[f.__qualname__].values()) |
| 396 |
|
| 397 |
def clear_overloads(): |
| 398 |
"""Clear all overloads in the registry.""" |
| 399 |
_overload_registry.clear() |
| 400 |
|
| 401 |
|
| 402 |
# This is not a real generic class. Don't use outside annotations. |
| 403 |
Type = typing.Type |
| 404 |
|
| 405 |
# Various ABCs mimicking those in collections.abc. |
| 406 |
# A few are simply re-exported for completeness. |
| 407 |
Awaitable = typing.Awaitable |
| 408 |
Coroutine = typing.Coroutine |
| 409 |
AsyncIterable = typing.AsyncIterable |
| 410 |
AsyncIterator = typing.AsyncIterator |
| 411 |
Deque = typing.Deque |
| 412 |
DefaultDict = typing.DefaultDict |
| 413 |
OrderedDict = typing.OrderedDict |
| 414 |
Counter = typing.Counter |
| 415 |
ChainMap = typing.ChainMap |
| 416 |
Text = typing.Text |
| 417 |
TYPE_CHECKING = typing.TYPE_CHECKING |
| 418 |
|
| 419 |
|
| 420 |
if sys.version_info >= (3, 13, 0, "beta"): |
| 421 |
from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator |
| 422 |
else: |
| 423 |
def _is_dunder(attr): |
| 424 |
return attr.startswith('__') and attr.endswith('__') |
| 425 |
|
| 426 |
# Python <3.9 doesn't have typing._SpecialGenericAlias |
| 427 |
_special_generic_alias_base = getattr( |
| 428 |
typing, "_SpecialGenericAlias", typing._GenericAlias |
| 429 |
) |
| 430 |
|
| 431 |
class _SpecialGenericAlias(_special_generic_alias_base, _root=True): |
| 432 |
def __init__(self, origin, nparams, *, inst=True, name=None, defaults=()): |
| 433 |
if _special_generic_alias_base is typing._GenericAlias: |
| 434 |
# Python <3.9 |
| 435 |
self.__origin__ = origin |
| 436 |
self._nparams = nparams |
| 437 |
super().__init__(origin, nparams, special=True, inst=inst, name=name) |
| 438 |
else: |
| 439 |
# Python >= 3.9 |
| 440 |
super().__init__(origin, nparams, inst=inst, name=name) |
| 441 |
self._defaults = defaults |
| 442 |
|
| 443 |
def __setattr__(self, attr, val): |
| 444 |
allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'} |
| 445 |
if _special_generic_alias_base is typing._GenericAlias: |
| 446 |
# Python <3.9 |
| 447 |
allowed_attrs.add("__origin__") |
| 448 |
if _is_dunder(attr) or attr in allowed_attrs: |
| 449 |
object.__setattr__(self, attr, val) |
| 450 |
else: |
| 451 |
setattr(self.__origin__, attr, val) |
| 452 |
|
| 453 |
@typing._tp_cache |
| 454 |
def __getitem__(self, params): |
| 455 |
if not isinstance(params, tuple): |
| 456 |
params = (params,) |
| 457 |
msg = "Parameters to generic types must be types." |
| 458 |
params = tuple(typing._type_check(p, msg) for p in params) |
| 459 |
if ( |
| 460 |
self._defaults |
| 461 |
and len(params) < self._nparams |
| 462 |
and len(params) + len(self._defaults) >= self._nparams |
| 463 |
): |
| 464 |
params = (*params, *self._defaults[len(params) - self._nparams:]) |
| 465 |
actual_len = len(params) |
| 466 |
|
| 467 |
if actual_len != self._nparams: |
| 468 |
if self._defaults: |
| 469 |
expected = f"at least {self._nparams - len(self._defaults)}" |
| 470 |
else: |
| 471 |
expected = str(self._nparams) |
| 472 |
if not self._nparams: |
| 473 |
raise TypeError(f"{self} is not a generic class") |
| 474 |
raise TypeError( |
| 475 |
f"Too {'many' if actual_len > self._nparams else 'few'}" |
| 476 |
f" arguments for {self};" |
| 477 |
f" actual {actual_len}, expected {expected}" |
| 478 |
) |
| 479 |
return self.copy_with(params) |
| 480 |
|
| 481 |
_NoneType = type(None) |
| 482 |
Generator = _SpecialGenericAlias( |
| 483 |
collections.abc.Generator, 3, defaults=(_NoneType, _NoneType) |
| 484 |
) |
| 485 |
AsyncGenerator = _SpecialGenericAlias( |
| 486 |
collections.abc.AsyncGenerator, 2, defaults=(_NoneType,) |
| 487 |
) |
| 488 |
ContextManager = _SpecialGenericAlias( |
| 489 |
contextlib.AbstractContextManager, |
| 490 |
2, |
| 491 |
name="ContextManager", |
| 492 |
defaults=(typing.Optional[bool],) |
| 493 |
) |
| 494 |
AsyncContextManager = _SpecialGenericAlias( |
| 495 |
contextlib.AbstractAsyncContextManager, |
| 496 |
2, |
| 497 |
name="AsyncContextManager", |
| 498 |
defaults=(typing.Optional[bool],) |
| 499 |
) |
| 500 |
|
| 501 |
|
| 502 |
_PROTO_ALLOWLIST = { |
| 503 |
'collections.abc': [ |
| 504 |
'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', |
| 505 |
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer', |
| 506 |
], |
| 507 |
'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'], |
| 508 |
'typing_extensions': ['Buffer'], |
| 509 |
} |
| 510 |
|
| 511 |
|
| 512 |
_EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | { |
| 513 |
"__match_args__", "__protocol_attrs__", "__non_callable_proto_members__", |
| 514 |
"__final__", |
| 515 |
} |
| 516 |
|
| 517 |
|
| 518 |
def _get_protocol_attrs(cls): |
| 519 |
attrs = set() |
| 520 |
for base in cls.__mro__[:-1]: # without object |
| 521 |
if base.__name__ in {'Protocol', 'Generic'}: |
| 522 |
continue |
| 523 |
annotations = getattr(base, '__annotations__', {}) |
| 524 |
for attr in (*base.__dict__, *annotations): |
| 525 |
if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS): |
| 526 |
attrs.add(attr) |
| 527 |
return attrs |
| 528 |
|
| 529 |
|
| 530 |
def _caller(depth=2): |
| 531 |
try: |
| 532 |
return sys._getframe(depth).f_globals.get('__name__', '__main__') |
| 533 |
except (AttributeError, ValueError): # For platforms without _getframe() |
| 534 |
return None |
| 535 |
|
| 536 |
|
| 537 |
# `__match_args__` attribute was removed from protocol members in 3.13, |
| 538 |
# we want to backport this change to older Python versions. |
| 539 |
if sys.version_info >= (3, 13): |
| 540 |
Protocol = typing.Protocol |
| 541 |
else: |
| 542 |
def _allow_reckless_class_checks(depth=3): |
| 543 |
"""Allow instance and class checks for special stdlib modules. |
| 544 |
The abc and functools modules indiscriminately call isinstance() and |
| 545 |
issubclass() on the whole MRO of a user class, which may contain protocols. |
| 546 |
""" |
| 547 |
return _caller(depth) in {'abc', 'functools', None} |
| 548 |
|
| 549 |
def _no_init(self, *args, **kwargs): |
| 550 |
if type(self)._is_protocol: |
| 551 |
raise TypeError('Protocols cannot be instantiated') |
| 552 |
|
| 553 |
def _type_check_issubclass_arg_1(arg): |
| 554 |
"""Raise TypeError if `arg` is not an instance of `type` |
| 555 |
in `issubclass(arg, <protocol>)`. |
| 556 |
|
| 557 |
In most cases, this is verified by type.__subclasscheck__. |
| 558 |
Checking it again unnecessarily would slow down issubclass() checks, |
| 559 |
so, we don't perform this check unless we absolutely have to. |
| 560 |
|
| 561 |
For various error paths, however, |
| 562 |
we want to ensure that *this* error message is shown to the user |
| 563 |
where relevant, rather than a typing.py-specific error message. |
| 564 |
""" |
| 565 |
if not isinstance(arg, type): |
| 566 |
# Same error message as for issubclass(1, int). |
| 567 |
raise TypeError('issubclass() arg 1 must be a class') |
| 568 |
|
| 569 |
# Inheriting from typing._ProtocolMeta isn't actually desirable, |
| 570 |
# but is necessary to allow typing.Protocol and typing_extensions.Protocol |
| 571 |
# to mix without getting TypeErrors about "metaclass conflict" |
| 572 |
class _ProtocolMeta(type(typing.Protocol)): |
| 573 |
# This metaclass is somewhat unfortunate, |
| 574 |
# but is necessary for several reasons... |
| 575 |
# |
| 576 |
# NOTE: DO NOT call super() in any methods in this class |
| 577 |
# That would call the methods on typing._ProtocolMeta on Python 3.8-3.11 |
| 578 |
# and those are slow |
| 579 |
def __new__(mcls, name, bases, namespace, **kwargs): |
| 580 |
if name == "Protocol" and len(bases) < 2: |
| 581 |
pass |
| 582 |
elif {Protocol, typing.Protocol} & set(bases): |
| 583 |
for base in bases: |
| 584 |
if not ( |
| 585 |
base in {object, typing.Generic, Protocol, typing.Protocol} |
| 586 |
or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, []) |
| 587 |
or is_protocol(base) |
| 588 |
): |
| 589 |
raise TypeError( |
| 590 |
f"Protocols can only inherit from other protocols, " |
| 591 |
f"got {base!r}" |
| 592 |
) |
| 593 |
return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs) |
| 594 |
|
| 595 |
def __init__(cls, *args, **kwargs): |
| 596 |
abc.ABCMeta.__init__(cls, *args, **kwargs) |
| 597 |
if getattr(cls, "_is_protocol", False): |
| 598 |
cls.__protocol_attrs__ = _get_protocol_attrs(cls) |
| 599 |
|
| 600 |
def __subclasscheck__(cls, other): |
| 601 |
if cls is Protocol: |
| 602 |
return type.__subclasscheck__(cls, other) |
| 603 |
if ( |
| 604 |
getattr(cls, '_is_protocol', False) |
| 605 |
and not _allow_reckless_class_checks() |
| 606 |
): |
| 607 |
if not getattr(cls, '_is_runtime_protocol', False): |
| 608 |
_type_check_issubclass_arg_1(other) |
| 609 |
raise TypeError( |
| 610 |
"Instance and class checks can only be used with " |
| 611 |
"@runtime_checkable protocols" |
| 612 |
) |
| 613 |
if ( |
| 614 |
# this attribute is set by @runtime_checkable: |
| 615 |
cls.__non_callable_proto_members__ |
| 616 |
and cls.__dict__.get("__subclasshook__") is _proto_hook |
| 617 |
): |
| 618 |
_type_check_issubclass_arg_1(other) |
| 619 |
non_method_attrs = sorted(cls.__non_callable_proto_members__) |
| 620 |
raise TypeError( |
| 621 |
"Protocols with non-method members don't support issubclass()." |
| 622 |
f" Non-method members: {str(non_method_attrs)[1:-1]}." |
| 623 |
) |
| 624 |
return abc.ABCMeta.__subclasscheck__(cls, other) |
| 625 |
|
| 626 |
def __instancecheck__(cls, instance): |
| 627 |
# We need this method for situations where attributes are |
| 628 |
# assigned in __init__. |
| 629 |
if cls is Protocol: |
| 630 |
return type.__instancecheck__(cls, instance) |
| 631 |
if not getattr(cls, "_is_protocol", False): |
| 632 |
# i.e., it's a concrete subclass of a protocol |
| 633 |
return abc.ABCMeta.__instancecheck__(cls, instance) |
| 634 |
|
| 635 |
if ( |
| 636 |
not getattr(cls, '_is_runtime_protocol', False) and |
| 637 |
not _allow_reckless_class_checks() |
| 638 |
): |
| 639 |
raise TypeError("Instance and class checks can only be used with" |
| 640 |
" @runtime_checkable protocols") |
| 641 |
|
| 642 |
if abc.ABCMeta.__instancecheck__(cls, instance): |
| 643 |
return True |
| 644 |
|
| 645 |
for attr in cls.__protocol_attrs__: |
| 646 |
try: |
| 647 |
val = inspect.getattr_static(instance, attr) |
| 648 |
except AttributeError: |
| 649 |
break |
| 650 |
# this attribute is set by @runtime_checkable: |
| 651 |
if val is None and attr not in cls.__non_callable_proto_members__: |
| 652 |
break |
| 653 |
else: |
| 654 |
return True |
| 655 |
|
| 656 |
return False |
| 657 |
|
| 658 |
def __eq__(cls, other): |
| 659 |
# Hack so that typing.Generic.__class_getitem__ |
| 660 |
# treats typing_extensions.Protocol |
| 661 |
# as equivalent to typing.Protocol |
| 662 |
if abc.ABCMeta.__eq__(cls, other) is True: |
| 663 |
return True |
| 664 |
return cls is Protocol and other is typing.Protocol |
| 665 |
|
| 666 |
# This has to be defined, or the abc-module cache |
| 667 |
# complains about classes with this metaclass being unhashable, |
| 668 |
# if we define only __eq__! |
| 669 |
def __hash__(cls) -> int: |
| 670 |
return type.__hash__(cls) |
| 671 |
|
| 672 |
@classmethod |
| 673 |
def _proto_hook(cls, other): |
| 674 |
if not cls.__dict__.get('_is_protocol', False): |
| 675 |
return NotImplemented |
| 676 |
|
| 677 |
for attr in cls.__protocol_attrs__: |
| 678 |
for base in other.__mro__: |
| 679 |
# Check if the members appears in the class dictionary... |
| 680 |
if attr in base.__dict__: |
| 681 |
if base.__dict__[attr] is None: |
| 682 |
return NotImplemented |
| 683 |
break |
| 684 |
|
| 685 |
# ...or in annotations, if it is a sub-protocol. |
| 686 |
annotations = getattr(base, '__annotations__', {}) |
| 687 |
if ( |
| 688 |
isinstance(annotations, collections.abc.Mapping) |
| 689 |
and attr in annotations |
| 690 |
and is_protocol(other) |
| 691 |
): |
| 692 |
break |
| 693 |
else: |
| 694 |
return NotImplemented |
| 695 |
return True |
| 696 |
|
| 697 |
class Protocol(typing.Generic, metaclass=_ProtocolMeta): |
| 698 |
__doc__ = typing.Protocol.__doc__ |
| 699 |
__slots__ = () |
| 700 |
_is_protocol = True |
| 701 |
_is_runtime_protocol = False |
| 702 |
|
| 703 |
def __init_subclass__(cls, *args, **kwargs): |
| 704 |
super().__init_subclass__(*args, **kwargs) |
| 705 |
|
| 706 |
# Determine if this is a protocol or a concrete subclass. |
| 707 |
if not cls.__dict__.get('_is_protocol', False): |
| 708 |
cls._is_protocol = any(b is Protocol for b in cls.__bases__) |
| 709 |
|
| 710 |
# Set (or override) the protocol subclass hook. |
| 711 |
if '__subclasshook__' not in cls.__dict__: |
| 712 |
cls.__subclasshook__ = _proto_hook |
| 713 |
|
| 714 |
# Prohibit instantiation for protocol classes |
| 715 |
if cls._is_protocol and cls.__init__ is Protocol.__init__: |
| 716 |
cls.__init__ = _no_init |
| 717 |
|
| 718 |
|
| 719 |
if sys.version_info >= (3, 13): |
| 720 |
runtime_checkable = typing.runtime_checkable |
| 721 |
else: |
| 722 |
def runtime_checkable(cls): |
| 723 |
"""Mark a protocol class as a runtime protocol. |
| 724 |
|
| 725 |
Such protocol can be used with isinstance() and issubclass(). |
| 726 |
Raise TypeError if applied to a non-protocol class. |
| 727 |
This allows a simple-minded structural check very similar to |
| 728 |
one trick ponies in collections.abc such as Iterable. |
| 729 |
|
| 730 |
For example:: |
| 731 |
|
| 732 |
@runtime_checkable |
| 733 |
class Closable(Protocol): |
| 734 |
def close(self): ... |
| 735 |
|
| 736 |
assert isinstance(open('/some/file'), Closable) |
| 737 |
|
| 738 |
Warning: this will check only the presence of the required methods, |
| 739 |
not their type signatures! |
| 740 |
""" |
| 741 |
if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False): |
| 742 |
raise TypeError(f'@runtime_checkable can be only applied to protocol classes,' |
| 743 |
f' got {cls!r}') |
| 744 |
cls._is_runtime_protocol = True |
| 745 |
|
| 746 |
# typing.Protocol classes on <=3.11 break if we execute this block, |
| 747 |
# because typing.Protocol classes on <=3.11 don't have a |
| 748 |
# `__protocol_attrs__` attribute, and this block relies on the |
| 749 |
# `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+ |
| 750 |
# break if we *don't* execute this block, because *they* assume that all |
| 751 |
# protocol classes have a `__non_callable_proto_members__` attribute |
| 752 |
# (which this block sets) |
| 753 |
if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2): |
| 754 |
# PEP 544 prohibits using issubclass() |
| 755 |
# with protocols that have non-method members. |
| 756 |
# See gh-113320 for why we compute this attribute here, |
| 757 |
# rather than in `_ProtocolMeta.__init__` |
| 758 |
cls.__non_callable_proto_members__ = set() |
| 759 |
for attr in cls.__protocol_attrs__: |
| 760 |
try: |
| 761 |
is_callable = callable(getattr(cls, attr, None)) |
| 762 |
except Exception as e: |
| 763 |
raise TypeError( |
| 764 |
f"Failed to determine whether protocol member {attr!r} " |
| 765 |
"is a method member" |
| 766 |
) from e |
| 767 |
else: |
| 768 |
if not is_callable: |
| 769 |
cls.__non_callable_proto_members__.add(attr) |
| 770 |
|
| 771 |
return cls |
| 772 |
|
| 773 |
|
| 774 |
# The "runtime" alias exists for backwards compatibility. |
| 775 |
runtime = runtime_checkable |
| 776 |
|
| 777 |
|
| 778 |
# Our version of runtime-checkable protocols is faster on Python 3.8-3.11 |
| 779 |
if sys.version_info >= (3, 12): |
| 780 |
SupportsInt = typing.SupportsInt |
| 781 |
SupportsFloat = typing.SupportsFloat |
| 782 |
SupportsComplex = typing.SupportsComplex |
| 783 |
SupportsBytes = typing.SupportsBytes |
| 784 |
SupportsIndex = typing.SupportsIndex |
| 785 |
SupportsAbs = typing.SupportsAbs |
| 786 |
SupportsRound = typing.SupportsRound |
| 787 |
else: |
| 788 |
@runtime_checkable |
| 789 |
class SupportsInt(Protocol): |
| 790 |
"""An ABC with one abstract method __int__.""" |
| 791 |
__slots__ = () |
| 792 |
|
| 793 |
@abc.abstractmethod |
| 794 |
def __int__(self) -> int: |
| 795 |
pass |
| 796 |
|
| 797 |
@runtime_checkable |
| 798 |
class SupportsFloat(Protocol): |
| 799 |
"""An ABC with one abstract method __float__.""" |
| 800 |
__slots__ = () |
| 801 |
|
| 802 |
@abc.abstractmethod |
| 803 |
def __float__(self) -> float: |
| 804 |
pass |
| 805 |
|
| 806 |
@runtime_checkable |
| 807 |
class SupportsComplex(Protocol): |
| 808 |
"""An ABC with one abstract method __complex__.""" |
| 809 |
__slots__ = () |
| 810 |
|
| 811 |
@abc.abstractmethod |
| 812 |
def __complex__(self) -> complex: |
| 813 |
pass |
| 814 |
|
| 815 |
@runtime_checkable |
| 816 |
class SupportsBytes(Protocol): |
| 817 |
"""An ABC with one abstract method __bytes__.""" |
| 818 |
__slots__ = () |
| 819 |
|
| 820 |
@abc.abstractmethod |
| 821 |
def __bytes__(self) -> bytes: |
| 822 |
pass |
| 823 |
|
| 824 |
@runtime_checkable |
| 825 |
class SupportsIndex(Protocol): |
| 826 |
__slots__ = () |
| 827 |
|
| 828 |
@abc.abstractmethod |
| 829 |
def __index__(self) -> int: |
| 830 |
pass |
| 831 |
|
| 832 |
@runtime_checkable |
| 833 |
class SupportsAbs(Protocol[T_co]): |
| 834 |
""" |
| 835 |
An ABC with one abstract method __abs__ that is covariant in its return type. |
| 836 |
""" |
| 837 |
__slots__ = () |
| 838 |
|
| 839 |
@abc.abstractmethod |
| 840 |
def __abs__(self) -> T_co: |
| 841 |
pass |
| 842 |
|
| 843 |
@runtime_checkable |
| 844 |
class SupportsRound(Protocol[T_co]): |
| 845 |
""" |
| 846 |
An ABC with one abstract method __round__ that is covariant in its return type. |
| 847 |
""" |
| 848 |
__slots__ = () |
| 849 |
|
| 850 |
@abc.abstractmethod |
| 851 |
def __round__(self, ndigits: int = 0) -> T_co: |
| 852 |
pass |
| 853 |
|
| 854 |
|
| 855 |
def _ensure_subclassable(mro_entries): |
| 856 |
def inner(func): |
| 857 |
if sys.implementation.name == "pypy" and sys.version_info < (3, 9): |
| 858 |
cls_dict = { |
| 859 |
"__call__": staticmethod(func), |
| 860 |
"__mro_entries__": staticmethod(mro_entries) |
| 861 |
} |
| 862 |
t = type(func.__name__, (), cls_dict) |
| 863 |
return functools.update_wrapper(t(), func) |
| 864 |
else: |
| 865 |
func.__mro_entries__ = mro_entries |
| 866 |
return func |
| 867 |
return inner |
| 868 |
|
| 869 |
|
| 870 |
# Update this to something like >=3.13.0b1 if and when |
| 871 |
# PEP 728 is implemented in CPython |
| 872 |
_PEP_728_IMPLEMENTED = False |
| 873 |
|
| 874 |
if _PEP_728_IMPLEMENTED: |
| 875 |
# The standard library TypedDict in Python 3.8 does not store runtime information |
| 876 |
# about which (if any) keys are optional. See https://bugs.python.org/issue38834 |
| 877 |
# The standard library TypedDict in Python 3.9.0/1 does not honour the "total" |
| 878 |
# keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 |
| 879 |
# The standard library TypedDict below Python 3.11 does not store runtime |
| 880 |
# information about optional and required keys when using Required or NotRequired. |
| 881 |
# Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11. |
| 882 |
# Aaaand on 3.12 we add __orig_bases__ to TypedDict |
| 883 |
# to enable better runtime introspection. |
| 884 |
# On 3.13 we deprecate some odd ways of creating TypedDicts. |
| 885 |
# Also on 3.13, PEP 705 adds the ReadOnly[] qualifier. |
| 886 |
# PEP 728 (still pending) makes more changes. |
| 887 |
TypedDict = typing.TypedDict |
| 888 |
_TypedDictMeta = typing._TypedDictMeta |
| 889 |
is_typeddict = typing.is_typeddict |
| 890 |
else: |
| 891 |
# 3.10.0 and later |
| 892 |
_TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters |
| 893 |
|
| 894 |
def _get_typeddict_qualifiers(annotation_type): |
| 895 |
while True: |
| 896 |
annotation_origin = get_origin(annotation_type) |
| 897 |
if annotation_origin is Annotated: |
| 898 |
annotation_args = get_args(annotation_type) |
| 899 |
if annotation_args: |
| 900 |
annotation_type = annotation_args[0] |
| 901 |
else: |
| 902 |
break |
| 903 |
elif annotation_origin is Required: |
| 904 |
yield Required |
| 905 |
annotation_type, = get_args(annotation_type) |
| 906 |
elif annotation_origin is NotRequired: |
| 907 |
yield NotRequired |
| 908 |
annotation_type, = get_args(annotation_type) |
| 909 |
elif annotation_origin is ReadOnly: |
| 910 |
yield ReadOnly |
| 911 |
annotation_type, = get_args(annotation_type) |
| 912 |
else: |
| 913 |
break |
| 914 |
|
| 915 |
class _TypedDictMeta(type): |
| 916 |
def __new__(cls, name, bases, ns, *, total=True, closed=False): |
| 917 |
"""Create new typed dict class object. |
| 918 |
|
| 919 |
This method is called when TypedDict is subclassed, |
| 920 |
or when TypedDict is instantiated. This way |
| 921 |
TypedDict supports all three syntax forms described in its docstring. |
| 922 |
Subclasses and instances of TypedDict return actual dictionaries. |
| 923 |
""" |
| 924 |
for base in bases: |
| 925 |
if type(base) is not _TypedDictMeta and base is not typing.Generic: |
| 926 |
raise TypeError('cannot inherit from both a TypedDict type ' |
| 927 |
'and a non-TypedDict base class') |
| 928 |
|
| 929 |
if any(issubclass(b, typing.Generic) for b in bases): |
| 930 |
generic_base = (typing.Generic,) |
| 931 |
else: |
| 932 |
generic_base = () |
| 933 |
|
| 934 |
# typing.py generally doesn't let you inherit from plain Generic, unless |
| 935 |
# the name of the class happens to be "Protocol" |
| 936 |
tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns) |
| 937 |
tp_dict.__name__ = name |
| 938 |
if tp_dict.__qualname__ == "Protocol": |
| 939 |
tp_dict.__qualname__ = name |
| 940 |
|
| 941 |
if not hasattr(tp_dict, '__orig_bases__'): |
| 942 |
tp_dict.__orig_bases__ = bases |
| 943 |
|
| 944 |
annotations = {} |
| 945 |
if "__annotations__" in ns: |
| 946 |
own_annotations = ns["__annotations__"] |
| 947 |
elif "__annotate__" in ns: |
| 948 |
# TODO: Use inspect.VALUE here, and make the annotations lazily evaluated |
| 949 |
own_annotations = ns["__annotate__"](1) |
| 950 |
else: |
| 951 |
own_annotations = {} |
| 952 |
msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" |
| 953 |
if _TAKES_MODULE: |
| 954 |
own_annotations = { |
| 955 |
n: typing._type_check(tp, msg, module=tp_dict.__module__) |
| 956 |
for n, tp in own_annotations.items() |
| 957 |
} |
| 958 |
else: |
| 959 |
own_annotations = { |
| 960 |
n: typing._type_check(tp, msg) |
| 961 |
for n, tp in own_annotations.items() |
| 962 |
} |
| 963 |
required_keys = set() |
| 964 |
optional_keys = set() |
| 965 |
readonly_keys = set() |
| 966 |
mutable_keys = set() |
| 967 |
extra_items_type = None |
| 968 |
|
| 969 |
for base in bases: |
| 970 |
base_dict = base.__dict__ |
| 971 |
|
| 972 |
annotations.update(base_dict.get('__annotations__', {})) |
| 973 |
required_keys.update(base_dict.get('__required_keys__', ())) |
| 974 |
optional_keys.update(base_dict.get('__optional_keys__', ())) |
| 975 |
readonly_keys.update(base_dict.get('__readonly_keys__', ())) |
| 976 |
mutable_keys.update(base_dict.get('__mutable_keys__', ())) |
| 977 |
base_extra_items_type = base_dict.get('__extra_items__', None) |
| 978 |
if base_extra_items_type is not None: |
| 979 |
extra_items_type = base_extra_items_type |
| 980 |
|
| 981 |
if closed and extra_items_type is None: |
| 982 |
extra_items_type = Never |
| 983 |
if closed and "__extra_items__" in own_annotations: |
| 984 |
annotation_type = own_annotations.pop("__extra_items__") |
| 985 |
qualifiers = set(_get_typeddict_qualifiers(annotation_type)) |
| 986 |
if Required in qualifiers: |
| 987 |
raise TypeError( |
| 988 |
"Special key __extra_items__ does not support " |
| 989 |
"Required" |
| 990 |
) |
| 991 |
if NotRequired in qualifiers: |
| 992 |
raise TypeError( |
| 993 |
"Special key __extra_items__ does not support " |
| 994 |
"NotRequired" |
| 995 |
) |
| 996 |
extra_items_type = annotation_type |
| 997 |
|
| 998 |
annotations.update(own_annotations) |
| 999 |
for annotation_key, annotation_type in own_annotations.items(): |
| 1000 |
qualifiers = set(_get_typeddict_qualifiers(annotation_type)) |
| 1001 |
|
| 1002 |
if Required in qualifiers: |
| 1003 |
required_keys.add(annotation_key) |
| 1004 |
elif NotRequired in qualifiers: |
| 1005 |
optional_keys.add(annotation_key) |
| 1006 |
elif total: |
| 1007 |
required_keys.add(annotation_key) |
| 1008 |
else: |
| 1009 |
optional_keys.add(annotation_key) |
| 1010 |
if ReadOnly in qualifiers: |
| 1011 |
mutable_keys.discard(annotation_key) |
| 1012 |
readonly_keys.add(annotation_key) |
| 1013 |
else: |
| 1014 |
mutable_keys.add(annotation_key) |
| 1015 |
readonly_keys.discard(annotation_key) |
| 1016 |
|
| 1017 |
tp_dict.__annotations__ = annotations |
| 1018 |
tp_dict.__required_keys__ = frozenset(required_keys) |
| 1019 |
tp_dict.__optional_keys__ = frozenset(optional_keys) |
| 1020 |
tp_dict.__readonly_keys__ = frozenset(readonly_keys) |
| 1021 |
tp_dict.__mutable_keys__ = frozenset(mutable_keys) |
| 1022 |
if not hasattr(tp_dict, '__total__'): |
| 1023 |
tp_dict.__total__ = total |
| 1024 |
tp_dict.__closed__ = closed |
| 1025 |
tp_dict.__extra_items__ = extra_items_type |
| 1026 |
return tp_dict |
| 1027 |
|
| 1028 |
__call__ = dict # static method |
| 1029 |
|
| 1030 |
def __subclasscheck__(cls, other): |
| 1031 |
# Typed dicts are only for static structural subtyping. |
| 1032 |
raise TypeError('TypedDict does not support instance and class checks') |
| 1033 |
|
| 1034 |
__instancecheck__ = __subclasscheck__ |
| 1035 |
|
| 1036 |
_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {}) |
| 1037 |
|
| 1038 |
@_ensure_subclassable(lambda bases: (_TypedDict,)) |
| 1039 |
def TypedDict(typename, fields=_marker, /, *, total=True, closed=False, **kwargs): |
| 1040 |
"""A simple typed namespace. At runtime it is equivalent to a plain dict. |
| 1041 |
|
| 1042 |
TypedDict creates a dictionary type such that a type checker will expect all |
| 1043 |
instances to have a certain set of keys, where each key is |
| 1044 |
associated with a value of a consistent type. This expectation |
| 1045 |
is not checked at runtime. |
| 1046 |
|
| 1047 |
Usage:: |
| 1048 |
|
| 1049 |
class Point2D(TypedDict): |
| 1050 |
x: int |
| 1051 |
y: int |
| 1052 |
label: str |
| 1053 |
|
| 1054 |
a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK |
| 1055 |
b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check |
| 1056 |
|
| 1057 |
assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') |
| 1058 |
|
| 1059 |
The type info can be accessed via the Point2D.__annotations__ dict, and |
| 1060 |
the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. |
| 1061 |
TypedDict supports an additional equivalent form:: |
| 1062 |
|
| 1063 |
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) |
| 1064 |
|
| 1065 |
By default, all keys must be present in a TypedDict. It is possible |
| 1066 |
to override this by specifying totality:: |
| 1067 |
|
| 1068 |
class Point2D(TypedDict, total=False): |
| 1069 |
x: int |
| 1070 |
y: int |
| 1071 |
|
| 1072 |
This means that a Point2D TypedDict can have any of the keys omitted. A type |
| 1073 |
checker is only expected to support a literal False or True as the value of |
| 1074 |
the total argument. True is the default, and makes all items defined in the |
| 1075 |
class body be required. |
| 1076 |
|
| 1077 |
The Required and NotRequired special forms can also be used to mark |
| 1078 |
individual keys as being required or not required:: |
| 1079 |
|
| 1080 |
class Point2D(TypedDict): |
| 1081 |
x: int # the "x" key must always be present (Required is the default) |
| 1082 |
y: NotRequired[int] # the "y" key can be omitted |
| 1083 |
|
| 1084 |
See PEP 655 for more details on Required and NotRequired. |
| 1085 |
""" |
| 1086 |
if fields is _marker or fields is None: |
| 1087 |
if fields is _marker: |
| 1088 |
deprecated_thing = "Failing to pass a value for the 'fields' parameter" |
| 1089 |
else: |
| 1090 |
deprecated_thing = "Passing `None` as the 'fields' parameter" |
| 1091 |
|
| 1092 |
example = f"`{typename} = TypedDict({typename!r}, {{}})`" |
| 1093 |
deprecation_msg = ( |
| 1094 |
f"{deprecated_thing} is deprecated and will be disallowed in " |
| 1095 |
"Python 3.15. To create a TypedDict class with 0 fields " |
| 1096 |
"using the functional syntax, pass an empty dictionary, e.g. " |
| 1097 |
) + example + "." |
| 1098 |
warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2) |
| 1099 |
if closed is not False and closed is not True: |
| 1100 |
kwargs["closed"] = closed |
| 1101 |
closed = False |
| 1102 |
fields = kwargs |
| 1103 |
elif kwargs: |
| 1104 |
raise TypeError("TypedDict takes either a dict or keyword arguments," |
| 1105 |
" but not both") |
| 1106 |
if kwargs: |
| 1107 |
if sys.version_info >= (3, 13): |
| 1108 |
raise TypeError("TypedDict takes no keyword arguments") |
| 1109 |
warnings.warn( |
| 1110 |
"The kwargs-based syntax for TypedDict definitions is deprecated " |
| 1111 |
"in Python 3.11, will be removed in Python 3.13, and may not be " |
| 1112 |
"understood by third-party type checkers.", |
| 1113 |
DeprecationWarning, |
| 1114 |
stacklevel=2, |
| 1115 |
) |
| 1116 |
|
| 1117 |
ns = {'__annotations__': dict(fields)} |
| 1118 |
module = _caller() |
| 1119 |
if module is not None: |
| 1120 |
# Setting correct module is necessary to make typed dict classes pickleable. |
| 1121 |
ns['__module__'] = module |
| 1122 |
|
| 1123 |
td = _TypedDictMeta(typename, (), ns, total=total, closed=closed) |
| 1124 |
td.__orig_bases__ = (TypedDict,) |
| 1125 |
return td |
| 1126 |
|
| 1127 |
if hasattr(typing, "_TypedDictMeta"): |
| 1128 |
_TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta) |
| 1129 |
else: |
| 1130 |
_TYPEDDICT_TYPES = (_TypedDictMeta,) |
| 1131 |
|
| 1132 |
def is_typeddict(tp): |
| 1133 |
"""Check if an annotation is a TypedDict class |
| 1134 |
|
| 1135 |
For example:: |
| 1136 |
class Film(TypedDict): |
| 1137 |
title: str |
| 1138 |
year: int |
| 1139 |
|
| 1140 |
is_typeddict(Film) # => True |
| 1141 |
is_typeddict(Union[list, str]) # => False |
| 1142 |
""" |
| 1143 |
# On 3.8, this would otherwise return True |
| 1144 |
if hasattr(typing, "TypedDict") and tp is typing.TypedDict: |
| 1145 |
return False |
| 1146 |
return isinstance(tp, _TYPEDDICT_TYPES) |
| 1147 |
|
| 1148 |
|
| 1149 |
if hasattr(typing, "assert_type"): |
| 1150 |
assert_type = typing.assert_type |
| 1151 |
|
| 1152 |
else: |
| 1153 |
def assert_type(val, typ, /): |
| 1154 |
"""Assert (to the type checker) that the value is of the given type. |
| 1155 |
|
| 1156 |
When the type checker encounters a call to assert_type(), it |
| 1157 |
emits an error if the value is not of the specified type:: |
| 1158 |
|
| 1159 |
def greet(name: str) -> None: |
| 1160 |
assert_type(name, str) # ok |
| 1161 |
assert_type(name, int) # type checker error |
| 1162 |
|
| 1163 |
At runtime this returns the first argument unchanged and otherwise |
| 1164 |
does nothing. |
| 1165 |
""" |
| 1166 |
return val |
| 1167 |
|
| 1168 |
|
| 1169 |
if hasattr(typing, "ReadOnly"): # 3.13+ |
| 1170 |
get_type_hints = typing.get_type_hints |
| 1171 |
else: # <=3.13 |
| 1172 |
# replaces _strip_annotations() |
| 1173 |
def _strip_extras(t): |
| 1174 |
"""Strips Annotated, Required and NotRequired from a given type.""" |
| 1175 |
if isinstance(t, _AnnotatedAlias): |
| 1176 |
return _strip_extras(t.__origin__) |
| 1177 |
if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly): |
| 1178 |
return _strip_extras(t.__args__[0]) |
| 1179 |
if isinstance(t, typing._GenericAlias): |
| 1180 |
stripped_args = tuple(_strip_extras(a) for a in t.__args__) |
| 1181 |
if stripped_args == t.__args__: |
| 1182 |
return t |
| 1183 |
return t.copy_with(stripped_args) |
| 1184 |
if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias): |
| 1185 |
stripped_args = tuple(_strip_extras(a) for a in t.__args__) |
| 1186 |
if stripped_args == t.__args__: |
| 1187 |
return t |
| 1188 |
return _types.GenericAlias(t.__origin__, stripped_args) |
| 1189 |
if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType): |
| 1190 |
stripped_args = tuple(_strip_extras(a) for a in t.__args__) |
| 1191 |
if stripped_args == t.__args__: |
| 1192 |
return t |
| 1193 |
return functools.reduce(operator.or_, stripped_args) |
| 1194 |
|
| 1195 |
return t |
| 1196 |
|
| 1197 |
def get_type_hints(obj, globalns=None, localns=None, include_extras=False): |
| 1198 |
"""Return type hints for an object. |
| 1199 |
|
| 1200 |
This is often the same as obj.__annotations__, but it handles |
| 1201 |
forward references encoded as string literals, adds Optional[t] if a |
| 1202 |
default value equal to None is set and recursively replaces all |
| 1203 |
'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T' |
| 1204 |
(unless 'include_extras=True'). |
| 1205 |
|
| 1206 |
The argument may be a module, class, method, or function. The annotations |
| 1207 |
are returned as a dictionary. For classes, annotations include also |
| 1208 |
inherited members. |
| 1209 |
|
| 1210 |
TypeError is raised if the argument is not of a type that can contain |
| 1211 |
annotations, and an empty dictionary is returned if no annotations are |
| 1212 |
present. |
| 1213 |
|
| 1214 |
BEWARE -- the behavior of globalns and localns is counterintuitive |
| 1215 |
(unless you are familiar with how eval() and exec() work). The |
| 1216 |
search order is locals first, then globals. |
| 1217 |
|
| 1218 |
- If no dict arguments are passed, an attempt is made to use the |
| 1219 |
globals from obj (or the respective module's globals for classes), |
| 1220 |
and these are also used as the locals. If the object does not appear |
| 1221 |
to have globals, an empty dictionary is used. |
| 1222 |
|
| 1223 |
- If one dict argument is passed, it is used for both globals and |
| 1224 |
locals. |
| 1225 |
|
| 1226 |
- If two dict arguments are passed, they specify globals and |
| 1227 |
locals, respectively. |
| 1228 |
""" |
| 1229 |
if hasattr(typing, "Annotated"): # 3.9+ |
| 1230 |
hint = typing.get_type_hints( |
| 1231 |
obj, globalns=globalns, localns=localns, include_extras=True |
| 1232 |
) |
| 1233 |
else: # 3.8 |
| 1234 |
hint = typing.get_type_hints(obj, globalns=globalns, localns=localns) |
| 1235 |
if include_extras: |
| 1236 |
return hint |
| 1237 |
return {k: _strip_extras(t) for k, t in hint.items()} |
| 1238 |
|
| 1239 |
|
| 1240 |
# Python 3.9+ has PEP 593 (Annotated) |
| 1241 |
if hasattr(typing, 'Annotated'): |
| 1242 |
Annotated = typing.Annotated |
| 1243 |
# Not exported and not a public API, but needed for get_origin() and get_args() |
| 1244 |
# to work. |
| 1245 |
_AnnotatedAlias = typing._AnnotatedAlias |
| 1246 |
# 3.8 |
| 1247 |
else: |
| 1248 |
class _AnnotatedAlias(typing._GenericAlias, _root=True): |
| 1249 |
"""Runtime representation of an annotated type. |
| 1250 |
|
| 1251 |
At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' |
| 1252 |
with extra annotations. The alias behaves like a normal typing alias, |
| 1253 |
instantiating is the same as instantiating the underlying type, binding |
| 1254 |
it to types is also the same. |
| 1255 |
""" |
| 1256 |
def __init__(self, origin, metadata): |
| 1257 |
if isinstance(origin, _AnnotatedAlias): |
| 1258 |
metadata = origin.__metadata__ + metadata |
| 1259 |
origin = origin.__origin__ |
| 1260 |
super().__init__(origin, origin) |
| 1261 |
self.__metadata__ = metadata |
| 1262 |
|
| 1263 |
def copy_with(self, params): |
| 1264 |
assert len(params) == 1 |
| 1265 |
new_type = params[0] |
| 1266 |
return _AnnotatedAlias(new_type, self.__metadata__) |
| 1267 |
|
| 1268 |
def __repr__(self): |
| 1269 |
return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, " |
| 1270 |
f"{', '.join(repr(a) for a in self.__metadata__)}]") |
| 1271 |
|
| 1272 |
def __reduce__(self): |
| 1273 |
return operator.getitem, ( |
| 1274 |
Annotated, (self.__origin__, *self.__metadata__) |
| 1275 |
) |
| 1276 |
|
| 1277 |
def __eq__(self, other): |
| 1278 |
if not isinstance(other, _AnnotatedAlias): |
| 1279 |
return NotImplemented |
| 1280 |
if self.__origin__ != other.__origin__: |
| 1281 |
return False |
| 1282 |
return self.__metadata__ == other.__metadata__ |
| 1283 |
|
| 1284 |
def __hash__(self): |
| 1285 |
return hash((self.__origin__, self.__metadata__)) |
| 1286 |
|
| 1287 |
class Annotated: |
| 1288 |
"""Add context specific metadata to a type. |
| 1289 |
|
| 1290 |
Example: Annotated[int, runtime_check.Unsigned] indicates to the |
| 1291 |
hypothetical runtime_check module that this type is an unsigned int. |
| 1292 |
Every other consumer of this type can ignore this metadata and treat |
| 1293 |
this type as int. |
| 1294 |
|
| 1295 |
The first argument to Annotated must be a valid type (and will be in |
| 1296 |
the __origin__ field), the remaining arguments are kept as a tuple in |
| 1297 |
the __extra__ field. |
| 1298 |
|
| 1299 |
Details: |
| 1300 |
|
| 1301 |
- It's an error to call `Annotated` with less than two arguments. |
| 1302 |
- Nested Annotated are flattened:: |
| 1303 |
|
| 1304 |
Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] |
| 1305 |
|
| 1306 |
- Instantiating an annotated type is equivalent to instantiating the |
| 1307 |
underlying type:: |
| 1308 |
|
| 1309 |
Annotated[C, Ann1](5) == C(5) |
| 1310 |
|
| 1311 |
- Annotated can be used as a generic type alias:: |
| 1312 |
|
| 1313 |
Optimized = Annotated[T, runtime.Optimize()] |
| 1314 |
Optimized[int] == Annotated[int, runtime.Optimize()] |
| 1315 |
|
| 1316 |
OptimizedList = Annotated[List[T], runtime.Optimize()] |
| 1317 |
OptimizedList[int] == Annotated[List[int], runtime.Optimize()] |
| 1318 |
""" |
| 1319 |
|
| 1320 |
__slots__ = () |
| 1321 |
|
| 1322 |
def __new__(cls, *args, **kwargs): |
| 1323 |
raise TypeError("Type Annotated cannot be instantiated.") |
| 1324 |
|
| 1325 |
@typing._tp_cache |
| 1326 |
def __class_getitem__(cls, params): |
| 1327 |
if not isinstance(params, tuple) or len(params) < 2: |
| 1328 |
raise TypeError("Annotated[...] should be used " |
| 1329 |
"with at least two arguments (a type and an " |
| 1330 |
"annotation).") |
| 1331 |
allowed_special_forms = (ClassVar, Final) |
| 1332 |
if get_origin(params[0]) in allowed_special_forms: |
| 1333 |
origin = params[0] |
| 1334 |
else: |
| 1335 |
msg = "Annotated[t, ...]: t must be a type." |
| 1336 |
origin = typing._type_check(params[0], msg) |
| 1337 |
metadata = tuple(params[1:]) |
| 1338 |
return _AnnotatedAlias(origin, metadata) |
| 1339 |
|
| 1340 |
def __init_subclass__(cls, *args, **kwargs): |
| 1341 |
raise TypeError( |
| 1342 |
f"Cannot subclass {cls.__module__}.Annotated" |
| 1343 |
) |
| 1344 |
|
| 1345 |
# Python 3.8 has get_origin() and get_args() but those implementations aren't |
| 1346 |
# Annotated-aware, so we can't use those. Python 3.9's versions don't support |
| 1347 |
# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do. |
| 1348 |
if sys.version_info[:2] >= (3, 10): |
| 1349 |
get_origin = typing.get_origin |
| 1350 |
get_args = typing.get_args |
| 1351 |
# 3.8-3.9 |
| 1352 |
else: |
| 1353 |
try: |
| 1354 |
# 3.9+ |
| 1355 |
from typing import _BaseGenericAlias |
| 1356 |
except ImportError: |
| 1357 |
_BaseGenericAlias = typing._GenericAlias |
| 1358 |
try: |
| 1359 |
# 3.9+ |
| 1360 |
from typing import GenericAlias as _typing_GenericAlias |
| 1361 |
except ImportError: |
| 1362 |
_typing_GenericAlias = typing._GenericAlias |
| 1363 |
|
| 1364 |
def get_origin(tp): |
| 1365 |
"""Get the unsubscripted version of a type. |
| 1366 |
|
| 1367 |
This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar |
| 1368 |
and Annotated. Return None for unsupported types. Examples:: |
| 1369 |
|
| 1370 |
get_origin(Literal[42]) is Literal |
| 1371 |
get_origin(int) is None |
| 1372 |
get_origin(ClassVar[int]) is ClassVar |
| 1373 |
get_origin(Generic) is Generic |
| 1374 |
get_origin(Generic[T]) is Generic |
| 1375 |
get_origin(Union[T, int]) is Union |
| 1376 |
get_origin(List[Tuple[T, T]][int]) == list |
| 1377 |
get_origin(P.args) is P |
| 1378 |
""" |
| 1379 |
if isinstance(tp, _AnnotatedAlias): |
| 1380 |
return Annotated |
| 1381 |
if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias, |
| 1382 |
ParamSpecArgs, ParamSpecKwargs)): |
| 1383 |
return tp.__origin__ |
| 1384 |
if tp is typing.Generic: |
| 1385 |
return typing.Generic |
| 1386 |
return None |
| 1387 |
|
| 1388 |
def get_args(tp): |
| 1389 |
"""Get type arguments with all substitutions performed. |
| 1390 |
|
| 1391 |
For unions, basic simplifications used by Union constructor are performed. |
| 1392 |
Examples:: |
| 1393 |
get_args(Dict[str, int]) == (str, int) |
| 1394 |
get_args(int) == () |
| 1395 |
get_args(Union[int, Union[T, int], str][int]) == (int, str) |
| 1396 |
get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) |
| 1397 |
get_args(Callable[[], T][int]) == ([], int) |
| 1398 |
""" |
| 1399 |
if isinstance(tp, _AnnotatedAlias): |
| 1400 |
return (tp.__origin__, *tp.__metadata__) |
| 1401 |
if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)): |
| 1402 |
if getattr(tp, "_special", False): |
| 1403 |
return () |
| 1404 |
res = tp.__args__ |
| 1405 |
if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: |
| 1406 |
res = (list(res[:-1]), res[-1]) |
| 1407 |
return res |
| 1408 |
return () |
| 1409 |
|
| 1410 |
|
| 1411 |
# 3.10+ |
| 1412 |
if hasattr(typing, 'TypeAlias'): |
| 1413 |
TypeAlias = typing.TypeAlias |
| 1414 |
# 3.9 |
| 1415 |
elif sys.version_info[:2] >= (3, 9): |
| 1416 |
@_ExtensionsSpecialForm |
| 1417 |
def TypeAlias(self, parameters): |
| 1418 |
"""Special marker indicating that an assignment should |
| 1419 |
be recognized as a proper type alias definition by type |
| 1420 |
checkers. |
| 1421 |
|
| 1422 |
For example:: |
| 1423 |
|
| 1424 |
Predicate: TypeAlias = Callable[..., bool] |
| 1425 |
|
| 1426 |
It's invalid when used anywhere except as in the example above. |
| 1427 |
""" |
| 1428 |
raise TypeError(f"{self} is not subscriptable") |
| 1429 |
# 3.8 |
| 1430 |
else: |
| 1431 |
TypeAlias = _ExtensionsSpecialForm( |
| 1432 |
'TypeAlias', |
| 1433 |
doc="""Special marker indicating that an assignment should |
| 1434 |
be recognized as a proper type alias definition by type |
| 1435 |
checkers. |
| 1436 |
|
| 1437 |
For example:: |
| 1438 |
|
| 1439 |
Predicate: TypeAlias = Callable[..., bool] |
| 1440 |
|
| 1441 |
It's invalid when used anywhere except as in the example |
| 1442 |
above.""" |
| 1443 |
) |
| 1444 |
|
| 1445 |
|
| 1446 |
if hasattr(typing, "NoDefault"): |
| 1447 |
NoDefault = typing.NoDefault |
| 1448 |
else: |
| 1449 |
class NoDefaultTypeMeta(type): |
| 1450 |
def __setattr__(cls, attr, value): |
| 1451 |
# TypeError is consistent with the behavior of NoneType |
| 1452 |
raise TypeError( |
| 1453 |
f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}" |
| 1454 |
) |
| 1455 |
|
| 1456 |
class NoDefaultType(metaclass=NoDefaultTypeMeta): |
| 1457 |
"""The type of the NoDefault singleton.""" |
| 1458 |
|
| 1459 |
__slots__ = () |
| 1460 |
|
| 1461 |
def __new__(cls): |
| 1462 |
return globals().get("NoDefault") or object.__new__(cls) |
| 1463 |
|
| 1464 |
def __repr__(self): |
| 1465 |
return "typing_extensions.NoDefault" |
| 1466 |
|
| 1467 |
def __reduce__(self): |
| 1468 |
return "NoDefault" |
| 1469 |
|
| 1470 |
NoDefault = NoDefaultType() |
| 1471 |
del NoDefaultType, NoDefaultTypeMeta |
| 1472 |
|
| 1473 |
|
| 1474 |
def _set_default(type_param, default): |
| 1475 |
type_param.has_default = lambda: default is not NoDefault |
| 1476 |
type_param.__default__ = default |
| 1477 |
|
| 1478 |
|
| 1479 |
def _set_module(typevarlike): |
| 1480 |
# for pickling: |
| 1481 |
def_mod = _caller(depth=3) |
| 1482 |
if def_mod != 'typing_extensions': |
| 1483 |
typevarlike.__module__ = def_mod |
| 1484 |
|
| 1485 |
|
| 1486 |
class _DefaultMixin: |
| 1487 |
"""Mixin for TypeVarLike defaults.""" |
| 1488 |
|
| 1489 |
__slots__ = () |
| 1490 |
__init__ = _set_default |
| 1491 |
|
| 1492 |
|
| 1493 |
# Classes using this metaclass must provide a _backported_typevarlike ClassVar |
| 1494 |
class _TypeVarLikeMeta(type): |
| 1495 |
def __instancecheck__(cls, __instance: Any) -> bool: |
| 1496 |
return isinstance(__instance, cls._backported_typevarlike) |
| 1497 |
|
| 1498 |
|
| 1499 |
if _PEP_696_IMPLEMENTED: |
| 1500 |
from typing import TypeVar |
| 1501 |
else: |
| 1502 |
# Add default and infer_variance parameters from PEP 696 and 695 |
| 1503 |
class TypeVar(metaclass=_TypeVarLikeMeta): |
| 1504 |
"""Type variable.""" |
| 1505 |
|
| 1506 |
_backported_typevarlike = typing.TypeVar |
| 1507 |
|
| 1508 |
def __new__(cls, name, *constraints, bound=None, |
| 1509 |
covariant=False, contravariant=False, |
| 1510 |
default=NoDefault, infer_variance=False): |
| 1511 |
if hasattr(typing, "TypeAliasType"): |
| 1512 |
# PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar |
| 1513 |
typevar = typing.TypeVar(name, *constraints, bound=bound, |
| 1514 |
covariant=covariant, contravariant=contravariant, |
| 1515 |
infer_variance=infer_variance) |
| 1516 |
else: |
| 1517 |
typevar = typing.TypeVar(name, *constraints, bound=bound, |
| 1518 |
covariant=covariant, contravariant=contravariant) |
| 1519 |
if infer_variance and (covariant or contravariant): |
| 1520 |
raise ValueError("Variance cannot be specified with infer_variance.") |
| 1521 |
typevar.__infer_variance__ = infer_variance |
| 1522 |
|
| 1523 |
_set_default(typevar, default) |
| 1524 |
_set_module(typevar) |
| 1525 |
|
| 1526 |
def _tvar_prepare_subst(alias, args): |
| 1527 |
if ( |
| 1528 |
typevar.has_default() |
| 1529 |
and alias.__parameters__.index(typevar) == len(args) |
| 1530 |
): |
| 1531 |
args += (typevar.__default__,) |
| 1532 |
return args |
| 1533 |
|
| 1534 |
typevar.__typing_prepare_subst__ = _tvar_prepare_subst |
| 1535 |
return typevar |
| 1536 |
|
| 1537 |
def __init_subclass__(cls) -> None: |
| 1538 |
raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type") |
| 1539 |
|
| 1540 |
|
| 1541 |
# Python 3.10+ has PEP 612 |
| 1542 |
if hasattr(typing, 'ParamSpecArgs'): |
| 1543 |
ParamSpecArgs = typing.ParamSpecArgs |
| 1544 |
ParamSpecKwargs = typing.ParamSpecKwargs |
| 1545 |
# 3.8-3.9 |
| 1546 |
else: |
| 1547 |
class _Immutable: |
| 1548 |
"""Mixin to indicate that object should not be copied.""" |
| 1549 |
__slots__ = () |
| 1550 |
|
| 1551 |
def __copy__(self): |
| 1552 |
return self |
| 1553 |
|
| 1554 |
def __deepcopy__(self, memo): |
| 1555 |
return self |
| 1556 |
|
| 1557 |
class ParamSpecArgs(_Immutable): |
| 1558 |
"""The args for a ParamSpec object. |
| 1559 |
|
| 1560 |
Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. |
| 1561 |
|
| 1562 |
ParamSpecArgs objects have a reference back to their ParamSpec: |
| 1563 |
|
| 1564 |
P.args.__origin__ is P |
| 1565 |
|
| 1566 |
This type is meant for runtime introspection and has no special meaning to |
| 1567 |
static type checkers. |
| 1568 |
""" |
| 1569 |
def __init__(self, origin): |
| 1570 |
self.__origin__ = origin |
| 1571 |
|
| 1572 |
def __repr__(self): |
| 1573 |
return f"{self.__origin__.__name__}.args" |
| 1574 |
|
| 1575 |
def __eq__(self, other): |
| 1576 |
if not isinstance(other, ParamSpecArgs): |
| 1577 |
return NotImplemented |
| 1578 |
return self.__origin__ == other.__origin__ |
| 1579 |
|
| 1580 |
class ParamSpecKwargs(_Immutable): |
| 1581 |
"""The kwargs for a ParamSpec object. |
| 1582 |
|
| 1583 |
Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. |
| 1584 |
|
| 1585 |
ParamSpecKwargs objects have a reference back to their ParamSpec: |
| 1586 |
|
| 1587 |
P.kwargs.__origin__ is P |
| 1588 |
|
| 1589 |
This type is meant for runtime introspection and has no special meaning to |
| 1590 |
static type checkers. |
| 1591 |
""" |
| 1592 |
def __init__(self, origin): |
| 1593 |
self.__origin__ = origin |
| 1594 |
|
| 1595 |
def __repr__(self): |
| 1596 |
return f"{self.__origin__.__name__}.kwargs" |
| 1597 |
|
| 1598 |
def __eq__(self, other): |
| 1599 |
if not isinstance(other, ParamSpecKwargs): |
| 1600 |
return NotImplemented |
| 1601 |
return self.__origin__ == other.__origin__ |
| 1602 |
|
| 1603 |
|
| 1604 |
if _PEP_696_IMPLEMENTED: |
| 1605 |
from typing import ParamSpec |
| 1606 |
|
| 1607 |
# 3.10+ |
| 1608 |
elif hasattr(typing, 'ParamSpec'): |
| 1609 |
|
| 1610 |
# Add default parameter - PEP 696 |
| 1611 |
class ParamSpec(metaclass=_TypeVarLikeMeta): |
| 1612 |
"""Parameter specification.""" |
| 1613 |
|
| 1614 |
_backported_typevarlike = typing.ParamSpec |
| 1615 |
|
| 1616 |
def __new__(cls, name, *, bound=None, |
| 1617 |
covariant=False, contravariant=False, |
| 1618 |
infer_variance=False, default=NoDefault): |
| 1619 |
if hasattr(typing, "TypeAliasType"): |
| 1620 |
# PEP 695 implemented, can pass infer_variance to typing.TypeVar |
| 1621 |
paramspec = typing.ParamSpec(name, bound=bound, |
| 1622 |
covariant=covariant, |
| 1623 |
contravariant=contravariant, |
| 1624 |
infer_variance=infer_variance) |
| 1625 |
else: |
| 1626 |
paramspec = typing.ParamSpec(name, bound=bound, |
| 1627 |
covariant=covariant, |
| 1628 |
contravariant=contravariant) |
| 1629 |
paramspec.__infer_variance__ = infer_variance |
| 1630 |
|
| 1631 |
_set_default(paramspec, default) |
| 1632 |
_set_module(paramspec) |
| 1633 |
|
| 1634 |
def _paramspec_prepare_subst(alias, args): |
| 1635 |
params = alias.__parameters__ |
| 1636 |
i = params.index(paramspec) |
| 1637 |
if i == len(args) and paramspec.has_default(): |
| 1638 |
args = [*args, paramspec.__default__] |
| 1639 |
if i >= len(args): |
| 1640 |
raise TypeError(f"Too few arguments for {alias}") |
| 1641 |
# Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612. |
| 1642 |
if len(params) == 1 and not typing._is_param_expr(args[0]): |
| 1643 |
assert i == 0 |
| 1644 |
args = (args,) |
| 1645 |
# Convert lists to tuples to help other libraries cache the results. |
| 1646 |
elif isinstance(args[i], list): |
| 1647 |
args = (*args[:i], tuple(args[i]), *args[i + 1:]) |
| 1648 |
return args |
| 1649 |
|
| 1650 |
paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst |
| 1651 |
return paramspec |
| 1652 |
|
| 1653 |
def __init_subclass__(cls) -> None: |
| 1654 |
raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") |
| 1655 |
|
| 1656 |
# 3.8-3.9 |
| 1657 |
else: |
| 1658 |
|
| 1659 |
# Inherits from list as a workaround for Callable checks in Python < 3.9.2. |
| 1660 |
class ParamSpec(list, _DefaultMixin): |
| 1661 |
"""Parameter specification variable. |
| 1662 |
|
| 1663 |
Usage:: |
| 1664 |
|
| 1665 |
P = ParamSpec('P') |
| 1666 |
|
| 1667 |
Parameter specification variables exist primarily for the benefit of static |
| 1668 |
type checkers. They are used to forward the parameter types of one |
| 1669 |
callable to another callable, a pattern commonly found in higher order |
| 1670 |
functions and decorators. They are only valid when used in ``Concatenate``, |
| 1671 |
or s the first argument to ``Callable``. In Python 3.10 and higher, |
| 1672 |
they are also supported in user-defined Generics at runtime. |
| 1673 |
See class Generic for more information on generic types. An |
| 1674 |
example for annotating a decorator:: |
| 1675 |
|
| 1676 |
T = TypeVar('T') |
| 1677 |
P = ParamSpec('P') |
| 1678 |
|
| 1679 |
def add_logging(f: Callable[P, T]) -> Callable[P, T]: |
| 1680 |
'''A type-safe decorator to add logging to a function.''' |
| 1681 |
def inner(*args: P.args, **kwargs: P.kwargs) -> T: |
| 1682 |
logging.info(f'{f.__name__} was called') |
| 1683 |
return f(*args, **kwargs) |
| 1684 |
return inner |
| 1685 |
|
| 1686 |
@add_logging |
| 1687 |
def add_two(x: float, y: float) -> float: |
| 1688 |
'''Add two numbers together.''' |
| 1689 |
return x + y |
| 1690 |
|
| 1691 |
Parameter specification variables defined with covariant=True or |
| 1692 |
contravariant=True can be used to declare covariant or contravariant |
| 1693 |
generic types. These keyword arguments are valid, but their actual semantics |
| 1694 |
are yet to be decided. See PEP 612 for details. |
| 1695 |
|
| 1696 |
Parameter specification variables can be introspected. e.g.: |
| 1697 |
|
| 1698 |
P.__name__ == 'T' |
| 1699 |
P.__bound__ == None |
| 1700 |
P.__covariant__ == False |
| 1701 |
P.__contravariant__ == False |
| 1702 |
|
| 1703 |
Note that only parameter specification variables defined in global scope can |
| 1704 |
be pickled. |
| 1705 |
""" |
| 1706 |
|
| 1707 |
# Trick Generic __parameters__. |
| 1708 |
__class__ = typing.TypeVar |
| 1709 |
|
| 1710 |
@property |
| 1711 |
def args(self): |
| 1712 |
return ParamSpecArgs(self) |
| 1713 |
|
| 1714 |
@property |
| 1715 |
def kwargs(self): |
| 1716 |
return ParamSpecKwargs(self) |
| 1717 |
|
| 1718 |
def __init__(self, name, *, bound=None, covariant=False, contravariant=False, |
| 1719 |
infer_variance=False, default=NoDefault): |
| 1720 |
list.__init__(self, [self]) |
| 1721 |
self.__name__ = name |
| 1722 |
self.__covariant__ = bool(covariant) |
| 1723 |
self.__contravariant__ = bool(contravariant) |
| 1724 |
self.__infer_variance__ = bool(infer_variance) |
| 1725 |
if bound: |
| 1726 |
self.__bound__ = typing._type_check(bound, 'Bound must be a type.') |
| 1727 |
else: |
| 1728 |
self.__bound__ = None |
| 1729 |
_DefaultMixin.__init__(self, default) |
| 1730 |
|
| 1731 |
# for pickling: |
| 1732 |
def_mod = _caller() |
| 1733 |
if def_mod != 'typing_extensions': |
| 1734 |
self.__module__ = def_mod |
| 1735 |
|
| 1736 |
def __repr__(self): |
| 1737 |
if self.__infer_variance__: |
| 1738 |
prefix = '' |
| 1739 |
elif self.__covariant__: |
| 1740 |
prefix = '+' |
| 1741 |
elif self.__contravariant__: |
| 1742 |
prefix = '-' |
| 1743 |
else: |
| 1744 |
prefix = '~' |
| 1745 |
return prefix + self.__name__ |
| 1746 |
|
| 1747 |
def __hash__(self): |
| 1748 |
return object.__hash__(self) |
| 1749 |
|
| 1750 |
def __eq__(self, other): |
| 1751 |
return self is other |
| 1752 |
|
| 1753 |
def __reduce__(self): |
| 1754 |
return self.__name__ |
| 1755 |
|
| 1756 |
# Hack to get typing._type_check to pass. |
| 1757 |
def __call__(self, *args, **kwargs): |
| 1758 |
pass |
| 1759 |
|
| 1760 |
|
| 1761 |
# 3.8-3.9 |
| 1762 |
if not hasattr(typing, 'Concatenate'): |
| 1763 |
# Inherits from list as a workaround for Callable checks in Python < 3.9.2. |
| 1764 |
class _ConcatenateGenericAlias(list): |
| 1765 |
|
| 1766 |
# Trick Generic into looking into this for __parameters__. |
| 1767 |
__class__ = typing._GenericAlias |
| 1768 |
|
| 1769 |
# Flag in 3.8. |
| 1770 |
_special = False |
| 1771 |
|
| 1772 |
def __init__(self, origin, args): |
| 1773 |
super().__init__(args) |
| 1774 |
self.__origin__ = origin |
| 1775 |
self.__args__ = args |
| 1776 |
|
| 1777 |
def __repr__(self): |
| 1778 |
_type_repr = typing._type_repr |
| 1779 |
return (f'{_type_repr(self.__origin__)}' |
| 1780 |
f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]') |
| 1781 |
|
| 1782 |
def __hash__(self): |
| 1783 |
return hash((self.__origin__, self.__args__)) |
| 1784 |
|
| 1785 |
# Hack to get typing._type_check to pass in Generic. |
| 1786 |
def __call__(self, *args, **kwargs): |
| 1787 |
pass |
| 1788 |
|
| 1789 |
@property |
| 1790 |
def __parameters__(self): |
| 1791 |
return tuple( |
| 1792 |
tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec)) |
| 1793 |
) |
| 1794 |
|
| 1795 |
|
| 1796 |
# 3.8-3.9 |
| 1797 |
@typing._tp_cache |
| 1798 |
def _concatenate_getitem(self, parameters): |
| 1799 |
if parameters == (): |
| 1800 |
raise TypeError("Cannot take a Concatenate of no types.") |
| 1801 |
if not isinstance(parameters, tuple): |
| 1802 |
parameters = (parameters,) |
| 1803 |
if not isinstance(parameters[-1], ParamSpec): |
| 1804 |
raise TypeError("The last parameter to Concatenate should be a " |
| 1805 |
"ParamSpec variable.") |
| 1806 |
msg = "Concatenate[arg, ...]: each arg must be a type." |
| 1807 |
parameters = tuple(typing._type_check(p, msg) for p in parameters) |
| 1808 |
return _ConcatenateGenericAlias(self, parameters) |
| 1809 |
|
| 1810 |
|
| 1811 |
# 3.10+ |
| 1812 |
if hasattr(typing, 'Concatenate'): |
| 1813 |
Concatenate = typing.Concatenate |
| 1814 |
_ConcatenateGenericAlias = typing._ConcatenateGenericAlias |
| 1815 |
# 3.9 |
| 1816 |
elif sys.version_info[:2] >= (3, 9): |
| 1817 |
@_ExtensionsSpecialForm |
| 1818 |
def Concatenate(self, parameters): |
| 1819 |
"""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a |
| 1820 |
higher order function which adds, removes or transforms parameters of a |
| 1821 |
callable. |
| 1822 |
|
| 1823 |
For example:: |
| 1824 |
|
| 1825 |
Callable[Concatenate[int, P], int] |
| 1826 |
|
| 1827 |
See PEP 612 for detailed information. |
| 1828 |
""" |
| 1829 |
return _concatenate_getitem(self, parameters) |
| 1830 |
# 3.8 |
| 1831 |
else: |
| 1832 |
class _ConcatenateForm(_ExtensionsSpecialForm, _root=True): |
| 1833 |
def __getitem__(self, parameters): |
| 1834 |
return _concatenate_getitem(self, parameters) |
| 1835 |
|
| 1836 |
Concatenate = _ConcatenateForm( |
| 1837 |
'Concatenate', |
| 1838 |
doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a |
| 1839 |
higher order function which adds, removes or transforms parameters of a |
| 1840 |
callable. |
| 1841 |
|
| 1842 |
For example:: |
| 1843 |
|
| 1844 |
Callable[Concatenate[int, P], int] |
| 1845 |
|
| 1846 |
See PEP 612 for detailed information. |
| 1847 |
""") |
| 1848 |
|
| 1849 |
# 3.10+ |
| 1850 |
if hasattr(typing, 'TypeGuard'): |
| 1851 |
TypeGuard = typing.TypeGuard |
| 1852 |
# 3.9 |
| 1853 |
elif sys.version_info[:2] >= (3, 9): |
| 1854 |
@_ExtensionsSpecialForm |
| 1855 |
def TypeGuard(self, parameters): |
| 1856 |
"""Special typing form used to annotate the return type of a user-defined |
| 1857 |
type guard function. ``TypeGuard`` only accepts a single type argument. |
| 1858 |
At runtime, functions marked this way should return a boolean. |
| 1859 |
|
| 1860 |
``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static |
| 1861 |
type checkers to determine a more precise type of an expression within a |
| 1862 |
program's code flow. Usually type narrowing is done by analyzing |
| 1863 |
conditional code flow and applying the narrowing to a block of code. The |
| 1864 |
conditional expression here is sometimes referred to as a "type guard". |
| 1865 |
|
| 1866 |
Sometimes it would be convenient to use a user-defined boolean function |
| 1867 |
as a type guard. Such a function should use ``TypeGuard[...]`` as its |
| 1868 |
return type to alert static type checkers to this intention. |
| 1869 |
|
| 1870 |
Using ``-> TypeGuard`` tells the static type checker that for a given |
| 1871 |
function: |
| 1872 |
|
| 1873 |
1. The return value is a boolean. |
| 1874 |
2. If the return value is ``True``, the type of its argument |
| 1875 |
is the type inside ``TypeGuard``. |
| 1876 |
|
| 1877 |
For example:: |
| 1878 |
|
| 1879 |
def is_str(val: Union[str, float]): |
| 1880 |
# "isinstance" type guard |
| 1881 |
if isinstance(val, str): |
| 1882 |
# Type of ``val`` is narrowed to ``str`` |
| 1883 |
... |
| 1884 |
else: |
| 1885 |
# Else, type of ``val`` is narrowed to ``float``. |
| 1886 |
... |
| 1887 |
|
| 1888 |
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower |
| 1889 |
form of ``TypeA`` (it can even be a wider form) and this may lead to |
| 1890 |
type-unsafe results. The main reason is to allow for things like |
| 1891 |
narrowing ``List[object]`` to ``List[str]`` even though the latter is not |
| 1892 |
a subtype of the former, since ``List`` is invariant. The responsibility of |
| 1893 |
writing type-safe type guards is left to the user. |
| 1894 |
|
| 1895 |
``TypeGuard`` also works with type variables. For more information, see |
| 1896 |
PEP 647 (User-Defined Type Guards). |
| 1897 |
""" |
| 1898 |
item = typing._type_check(parameters, f'{self} accepts only a single type.') |
| 1899 |
return typing._GenericAlias(self, (item,)) |
| 1900 |
# 3.8 |
| 1901 |
else: |
| 1902 |
class _TypeGuardForm(_ExtensionsSpecialForm, _root=True): |
| 1903 |
def __getitem__(self, parameters): |
| 1904 |
item = typing._type_check(parameters, |
| 1905 |
f'{self._name} accepts only a single type') |
| 1906 |
return typing._GenericAlias(self, (item,)) |
| 1907 |
|
| 1908 |
TypeGuard = _TypeGuardForm( |
| 1909 |
'TypeGuard', |
| 1910 |
doc="""Special typing form used to annotate the return type of a user-defined |
| 1911 |
type guard function. ``TypeGuard`` only accepts a single type argument. |
| 1912 |
At runtime, functions marked this way should return a boolean. |
| 1913 |
|
| 1914 |
``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static |
| 1915 |
type checkers to determine a more precise type of an expression within a |
| 1916 |
program's code flow. Usually type narrowing is done by analyzing |
| 1917 |
conditional code flow and applying the narrowing to a block of code. The |
| 1918 |
conditional expression here is sometimes referred to as a "type guard". |
| 1919 |
|
| 1920 |
Sometimes it would be convenient to use a user-defined boolean function |
| 1921 |
as a type guard. Such a function should use ``TypeGuard[...]`` as its |
| 1922 |
return type to alert static type checkers to this intention. |
| 1923 |
|
| 1924 |
Using ``-> TypeGuard`` tells the static type checker that for a given |
| 1925 |
function: |
| 1926 |
|
| 1927 |
1. The return value is a boolean. |
| 1928 |
2. If the return value is ``True``, the type of its argument |
| 1929 |
is the type inside ``TypeGuard``. |
| 1930 |
|
| 1931 |
For example:: |
| 1932 |
|
| 1933 |
def is_str(val: Union[str, float]): |
| 1934 |
# "isinstance" type guard |
| 1935 |
if isinstance(val, str): |
| 1936 |
# Type of ``val`` is narrowed to ``str`` |
| 1937 |
... |
| 1938 |
else: |
| 1939 |
# Else, type of ``val`` is narrowed to ``float``. |
| 1940 |
... |
| 1941 |
|
| 1942 |
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower |
| 1943 |
form of ``TypeA`` (it can even be a wider form) and this may lead to |
| 1944 |
type-unsafe results. The main reason is to allow for things like |
| 1945 |
narrowing ``List[object]`` to ``List[str]`` even though the latter is not |
| 1946 |
a subtype of the former, since ``List`` is invariant. The responsibility of |
| 1947 |
writing type-safe type guards is left to the user. |
| 1948 |
|
| 1949 |
``TypeGuard`` also works with type variables. For more information, see |
| 1950 |
PEP 647 (User-Defined Type Guards). |
| 1951 |
""") |
| 1952 |
|
| 1953 |
# 3.13+ |
| 1954 |
if hasattr(typing, 'TypeIs'): |
| 1955 |
TypeIs = typing.TypeIs |
| 1956 |
# 3.9 |
| 1957 |
elif sys.version_info[:2] >= (3, 9): |
| 1958 |
@_ExtensionsSpecialForm |
| 1959 |
def TypeIs(self, parameters): |
| 1960 |
"""Special typing form used to annotate the return type of a user-defined |
| 1961 |
type narrower function. ``TypeIs`` only accepts a single type argument. |
| 1962 |
At runtime, functions marked this way should return a boolean. |
| 1963 |
|
| 1964 |
``TypeIs`` aims to benefit *type narrowing* -- a technique used by static |
| 1965 |
type checkers to determine a more precise type of an expression within a |
| 1966 |
program's code flow. Usually type narrowing is done by analyzing |
| 1967 |
conditional code flow and applying the narrowing to a block of code. The |
| 1968 |
conditional expression here is sometimes referred to as a "type guard". |
| 1969 |
|
| 1970 |
Sometimes it would be convenient to use a user-defined boolean function |
| 1971 |
as a type guard. Such a function should use ``TypeIs[...]`` as its |
| 1972 |
return type to alert static type checkers to this intention. |
| 1973 |
|
| 1974 |
Using ``-> TypeIs`` tells the static type checker that for a given |
| 1975 |
function: |
| 1976 |
|
| 1977 |
1. The return value is a boolean. |
| 1978 |
2. If the return value is ``True``, the type of its argument |
| 1979 |
is the intersection of the type inside ``TypeGuard`` and the argument's |
| 1980 |
previously known type. |
| 1981 |
|
| 1982 |
For example:: |
| 1983 |
|
| 1984 |
def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]: |
| 1985 |
return hasattr(val, '__await__') |
| 1986 |
|
| 1987 |
def f(val: Union[int, Awaitable[int]]) -> int: |
| 1988 |
if is_awaitable(val): |
| 1989 |
assert_type(val, Awaitable[int]) |
| 1990 |
else: |
| 1991 |
assert_type(val, int) |
| 1992 |
|
| 1993 |
``TypeIs`` also works with type variables. For more information, see |
| 1994 |
PEP 742 (Narrowing types with TypeIs). |
| 1995 |
""" |
| 1996 |
item = typing._type_check(parameters, f'{self} accepts only a single type.') |
| 1997 |
return typing._GenericAlias(self, (item,)) |
| 1998 |
# 3.8 |
| 1999 |
else: |
| 2000 |
class _TypeIsForm(_ExtensionsSpecialForm, _root=True): |
| 2001 |
def __getitem__(self, parameters): |
| 2002 |
item = typing._type_check(parameters, |
| 2003 |
f'{self._name} accepts only a single type') |
| 2004 |
return typing._GenericAlias(self, (item,)) |
| 2005 |
|
| 2006 |
TypeIs = _TypeIsForm( |
| 2007 |
'TypeIs', |
| 2008 |
doc="""Special typing form used to annotate the return type of a user-defined |
| 2009 |
type narrower function. ``TypeIs`` only accepts a single type argument. |
| 2010 |
At runtime, functions marked this way should return a boolean. |
| 2011 |
|
| 2012 |
``TypeIs`` aims to benefit *type narrowing* -- a technique used by static |
| 2013 |
type checkers to determine a more precise type of an expression within a |
| 2014 |
program's code flow. Usually type narrowing is done by analyzing |
| 2015 |
conditional code flow and applying the narrowing to a block of code. The |
| 2016 |
conditional expression here is sometimes referred to as a "type guard". |
| 2017 |
|
| 2018 |
Sometimes it would be convenient to use a user-defined boolean function |
| 2019 |
as a type guard. Such a function should use ``TypeIs[...]`` as its |
| 2020 |
return type to alert static type checkers to this intention. |
| 2021 |
|
| 2022 |
Using ``-> TypeIs`` tells the static type checker that for a given |
| 2023 |
function: |
| 2024 |
|
| 2025 |
1. The return value is a boolean. |
| 2026 |
2. If the return value is ``True``, the type of its argument |
| 2027 |
is the intersection of the type inside ``TypeGuard`` and the argument's |
| 2028 |
previously known type. |
| 2029 |
|
| 2030 |
For example:: |
| 2031 |
|
| 2032 |
def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]: |
| 2033 |
return hasattr(val, '__await__') |
| 2034 |
|
| 2035 |
def f(val: Union[int, Awaitable[int]]) -> int: |
| 2036 |
if is_awaitable(val): |
| 2037 |
assert_type(val, Awaitable[int]) |
| 2038 |
else: |
| 2039 |
assert_type(val, int) |
| 2040 |
|
| 2041 |
``TypeIs`` also works with type variables. For more information, see |
| 2042 |
PEP 742 (Narrowing types with TypeIs). |
| 2043 |
""") |
| 2044 |
|
| 2045 |
|
| 2046 |
# Vendored from cpython typing._SpecialFrom |
| 2047 |
class _SpecialForm(typing._Final, _root=True): |
| 2048 |
__slots__ = ('_name', '__doc__', '_getitem') |
| 2049 |
|
| 2050 |
def __init__(self, getitem): |
| 2051 |
self._getitem = getitem |
| 2052 |
self._name = getitem.__name__ |
| 2053 |
self.__doc__ = getitem.__doc__ |
| 2054 |
|
| 2055 |
def __getattr__(self, item): |
| 2056 |
if item in {'__name__', '__qualname__'}: |
| 2057 |
return self._name |
| 2058 |
|
| 2059 |
raise AttributeError(item) |
| 2060 |
|
| 2061 |
def __mro_entries__(self, bases): |
| 2062 |
raise TypeError(f"Cannot subclass {self!r}") |
| 2063 |
|
| 2064 |
def __repr__(self): |
| 2065 |
return f'typing_extensions.{self._name}' |
| 2066 |
|
| 2067 |
def __reduce__(self): |
| 2068 |
return self._name |
| 2069 |
|
| 2070 |
def __call__(self, *args, **kwds): |
| 2071 |
raise TypeError(f"Cannot instantiate {self!r}") |
| 2072 |
|
| 2073 |
def __or__(self, other): |
| 2074 |
return typing.Union[self, other] |
| 2075 |
|
| 2076 |
def __ror__(self, other): |
| 2077 |
return typing.Union[other, self] |
| 2078 |
|
| 2079 |
def __instancecheck__(self, obj): |
| 2080 |
raise TypeError(f"{self} cannot be used with isinstance()") |
| 2081 |
|
| 2082 |
def __subclasscheck__(self, cls): |
| 2083 |
raise TypeError(f"{self} cannot be used with issubclass()") |
| 2084 |
|
| 2085 |
@typing._tp_cache |
| 2086 |
def __getitem__(self, parameters): |
| 2087 |
return self._getitem(self, parameters) |
| 2088 |
|
| 2089 |
|
| 2090 |
if hasattr(typing, "LiteralString"): # 3.11+ |
| 2091 |
LiteralString = typing.LiteralString |
| 2092 |
else: |
| 2093 |
@_SpecialForm |
| 2094 |
def LiteralString(self, params): |
| 2095 |
"""Represents an arbitrary literal string. |
| 2096 |
|
| 2097 |
Example:: |
| 2098 |
|
| 2099 |
from typing_extensions import LiteralString |
| 2100 |
|
| 2101 |
def query(sql: LiteralString) -> ...: |
| 2102 |
... |
| 2103 |
|
| 2104 |
query("SELECT * FROM table") # ok |
| 2105 |
query(f"SELECT * FROM {input()}") # not ok |
| 2106 |
|
| 2107 |
See PEP 675 for details. |
| 2108 |
|
| 2109 |
""" |
| 2110 |
raise TypeError(f"{self} is not subscriptable") |
| 2111 |
|
| 2112 |
|
| 2113 |
if hasattr(typing, "Self"): # 3.11+ |
| 2114 |
Self = typing.Self |
| 2115 |
else: |
| 2116 |
@_SpecialForm |
| 2117 |
def Self(self, params): |
| 2118 |
"""Used to spell the type of "self" in classes. |
| 2119 |
|
| 2120 |
Example:: |
| 2121 |
|
| 2122 |
from typing import Self |
| 2123 |
|
| 2124 |
class ReturnsSelf: |
| 2125 |
def parse(self, data: bytes) -> Self: |
| 2126 |
... |
| 2127 |
return self |
| 2128 |
|
| 2129 |
""" |
| 2130 |
|
| 2131 |
raise TypeError(f"{self} is not subscriptable") |
| 2132 |
|
| 2133 |
|
| 2134 |
if hasattr(typing, "Never"): # 3.11+ |
| 2135 |
Never = typing.Never |
| 2136 |
else: |
| 2137 |
@_SpecialForm |
| 2138 |
def Never(self, params): |
| 2139 |
"""The bottom type, a type that has no members. |
| 2140 |
|
| 2141 |
This can be used to define a function that should never be |
| 2142 |
called, or a function that never returns:: |
| 2143 |
|
| 2144 |
from typing_extensions import Never |
| 2145 |
|
| 2146 |
def never_call_me(arg: Never) -> None: |
| 2147 |
pass |
| 2148 |
|
| 2149 |
def int_or_str(arg: int | str) -> None: |
| 2150 |
never_call_me(arg) # type checker error |
| 2151 |
match arg: |
| 2152 |
case int(): |
| 2153 |
print("It's an int") |
| 2154 |
case str(): |
| 2155 |
print("It's a str") |
| 2156 |
case _: |
| 2157 |
never_call_me(arg) # ok, arg is of type Never |
| 2158 |
|
| 2159 |
""" |
| 2160 |
|
| 2161 |
raise TypeError(f"{self} is not subscriptable") |
| 2162 |
|
| 2163 |
|
| 2164 |
if hasattr(typing, 'Required'): # 3.11+ |
| 2165 |
Required = typing.Required |
| 2166 |
NotRequired = typing.NotRequired |
| 2167 |
elif sys.version_info[:2] >= (3, 9): # 3.9-3.10 |
| 2168 |
@_ExtensionsSpecialForm |
| 2169 |
def Required(self, parameters): |
| 2170 |
"""A special typing construct to mark a key of a total=False TypedDict |
| 2171 |
as required. For example: |
| 2172 |
|
| 2173 |
class Movie(TypedDict, total=False): |
| 2174 |
title: Required[str] |
| 2175 |
year: int |
| 2176 |
|
| 2177 |
m = Movie( |
| 2178 |
title='The Matrix', # typechecker error if key is omitted |
| 2179 |
year=1999, |
| 2180 |
) |
| 2181 |
|
| 2182 |
There is no runtime checking that a required key is actually provided |
| 2183 |
when instantiating a related TypedDict. |
| 2184 |
""" |
| 2185 |
item = typing._type_check(parameters, f'{self._name} accepts only a single type.') |
| 2186 |
return typing._GenericAlias(self, (item,)) |
| 2187 |
|
| 2188 |
@_ExtensionsSpecialForm |
| 2189 |
def NotRequired(self, parameters): |
| 2190 |
"""A special typing construct to mark a key of a TypedDict as |
| 2191 |
potentially missing. For example: |
| 2192 |
|
| 2193 |
class Movie(TypedDict): |
| 2194 |
title: str |
| 2195 |
year: NotRequired[int] |
| 2196 |
|
| 2197 |
m = Movie( |
| 2198 |
title='The Matrix', # typechecker error if key is omitted |
| 2199 |
year=1999, |
| 2200 |
) |
| 2201 |
""" |
| 2202 |
item = typing._type_check(parameters, f'{self._name} accepts only a single type.') |
| 2203 |
return typing._GenericAlias(self, (item,)) |
| 2204 |
|
| 2205 |
else: # 3.8 |
| 2206 |
class _RequiredForm(_ExtensionsSpecialForm, _root=True): |
| 2207 |
def __getitem__(self, parameters): |
| 2208 |
item = typing._type_check(parameters, |
| 2209 |
f'{self._name} accepts only a single type.') |
| 2210 |
return typing._GenericAlias(self, (item,)) |
| 2211 |
|
| 2212 |
Required = _RequiredForm( |
| 2213 |
'Required', |
| 2214 |
doc="""A special typing construct to mark a key of a total=False TypedDict |
| 2215 |
as required. For example: |
| 2216 |
|
| 2217 |
class Movie(TypedDict, total=False): |
| 2218 |
title: Required[str] |
| 2219 |
year: int |
| 2220 |
|
| 2221 |
m = Movie( |
| 2222 |
title='The Matrix', # typechecker error if key is omitted |
| 2223 |
year=1999, |
| 2224 |
) |
| 2225 |
|
| 2226 |
There is no runtime checking that a required key is actually provided |
| 2227 |
when instantiating a related TypedDict. |
| 2228 |
""") |
| 2229 |
NotRequired = _RequiredForm( |
| 2230 |
'NotRequired', |
| 2231 |
doc="""A special typing construct to mark a key of a TypedDict as |
| 2232 |
potentially missing. For example: |
| 2233 |
|
| 2234 |
class Movie(TypedDict): |
| 2235 |
title: str |
| 2236 |
year: NotRequired[int] |
| 2237 |
|
| 2238 |
m = Movie( |
| 2239 |
title='The Matrix', # typechecker error if key is omitted |
| 2240 |
year=1999, |
| 2241 |
) |
| 2242 |
""") |
| 2243 |
|
| 2244 |
|
| 2245 |
if hasattr(typing, 'ReadOnly'): |
| 2246 |
ReadOnly = typing.ReadOnly |
| 2247 |
elif sys.version_info[:2] >= (3, 9): # 3.9-3.12 |
| 2248 |
@_ExtensionsSpecialForm |
| 2249 |
def ReadOnly(self, parameters): |
| 2250 |
"""A special typing construct to mark an item of a TypedDict as read-only. |
| 2251 |
|
| 2252 |
For example: |
| 2253 |
|
| 2254 |
class Movie(TypedDict): |
| 2255 |
title: ReadOnly[str] |
| 2256 |
year: int |
| 2257 |
|
| 2258 |
def mutate_movie(m: Movie) -> None: |
| 2259 |
m["year"] = 1992 # allowed |
| 2260 |
m["title"] = "The Matrix" # typechecker error |
| 2261 |
|
| 2262 |
There is no runtime checking for this property. |
| 2263 |
""" |
| 2264 |
item = typing._type_check(parameters, f'{self._name} accepts only a single type.') |
| 2265 |
return typing._GenericAlias(self, (item,)) |
| 2266 |
|
| 2267 |
else: # 3.8 |
| 2268 |
class _ReadOnlyForm(_ExtensionsSpecialForm, _root=True): |
| 2269 |
def __getitem__(self, parameters): |
| 2270 |
item = typing._type_check(parameters, |
| 2271 |
f'{self._name} accepts only a single type.') |
| 2272 |
return typing._GenericAlias(self, (item,)) |
| 2273 |
|
| 2274 |
ReadOnly = _ReadOnlyForm( |
| 2275 |
'ReadOnly', |
| 2276 |
doc="""A special typing construct to mark a key of a TypedDict as read-only. |
| 2277 |
|
| 2278 |
For example: |
| 2279 |
|
| 2280 |
class Movie(TypedDict): |
| 2281 |
title: ReadOnly[str] |
| 2282 |
year: int |
| 2283 |
|
| 2284 |
def mutate_movie(m: Movie) -> None: |
| 2285 |
m["year"] = 1992 # allowed |
| 2286 |
m["title"] = "The Matrix" # typechecker error |
| 2287 |
|
| 2288 |
There is no runtime checking for this propery. |
| 2289 |
""") |
| 2290 |
|
| 2291 |
|
| 2292 |
_UNPACK_DOC = """\ |
| 2293 |
Type unpack operator. |
| 2294 |
|
| 2295 |
The type unpack operator takes the child types from some container type, |
| 2296 |
such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For |
| 2297 |
example: |
| 2298 |
|
| 2299 |
# For some generic class `Foo`: |
| 2300 |
Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str] |
| 2301 |
|
| 2302 |
Ts = TypeVarTuple('Ts') |
| 2303 |
# Specifies that `Bar` is generic in an arbitrary number of types. |
| 2304 |
# (Think of `Ts` as a tuple of an arbitrary number of individual |
| 2305 |
# `TypeVar`s, which the `Unpack` is 'pulling out' directly into the |
| 2306 |
# `Generic[]`.) |
| 2307 |
class Bar(Generic[Unpack[Ts]]): ... |
| 2308 |
Bar[int] # Valid |
| 2309 |
Bar[int, str] # Also valid |
| 2310 |
|
| 2311 |
From Python 3.11, this can also be done using the `*` operator: |
| 2312 |
|
| 2313 |
Foo[*tuple[int, str]] |
| 2314 |
class Bar(Generic[*Ts]): ... |
| 2315 |
|
| 2316 |
The operator can also be used along with a `TypedDict` to annotate |
| 2317 |
`**kwargs` in a function signature. For instance: |
| 2318 |
|
| 2319 |
class Movie(TypedDict): |
| 2320 |
name: str |
| 2321 |
year: int |
| 2322 |
|
| 2323 |
# This function expects two keyword arguments - *name* of type `str` and |
| 2324 |
# *year* of type `int`. |
| 2325 |
def foo(**kwargs: Unpack[Movie]): ... |
| 2326 |
|
| 2327 |
Note that there is only some runtime checking of this operator. Not |
| 2328 |
everything the runtime allows may be accepted by static type checkers. |
| 2329 |
|
| 2330 |
For more information, see PEP 646 and PEP 692. |
| 2331 |
""" |
| 2332 |
|
| 2333 |
|
| 2334 |
if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[] |
| 2335 |
Unpack = typing.Unpack |
| 2336 |
|
| 2337 |
def _is_unpack(obj): |
| 2338 |
return get_origin(obj) is Unpack |
| 2339 |
|
| 2340 |
elif sys.version_info[:2] >= (3, 9): # 3.9+ |
| 2341 |
class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True): |
| 2342 |
def __init__(self, getitem): |
| 2343 |
super().__init__(getitem) |
| 2344 |
self.__doc__ = _UNPACK_DOC |
| 2345 |
|
| 2346 |
class _UnpackAlias(typing._GenericAlias, _root=True): |
| 2347 |
__class__ = typing.TypeVar |
| 2348 |
|
| 2349 |
@property |
| 2350 |
def __typing_unpacked_tuple_args__(self): |
| 2351 |
assert self.__origin__ is Unpack |
| 2352 |
assert len(self.__args__) == 1 |
| 2353 |
arg, = self.__args__ |
| 2354 |
if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)): |
| 2355 |
if arg.__origin__ is not tuple: |
| 2356 |
raise TypeError("Unpack[...] must be used with a tuple type") |
| 2357 |
return arg.__args__ |
| 2358 |
return None |
| 2359 |
|
| 2360 |
@_UnpackSpecialForm |
| 2361 |
def Unpack(self, parameters): |
| 2362 |
item = typing._type_check(parameters, f'{self._name} accepts only a single type.') |
| 2363 |
return _UnpackAlias(self, (item,)) |
| 2364 |
|
| 2365 |
def _is_unpack(obj): |
| 2366 |
return isinstance(obj, _UnpackAlias) |
| 2367 |
|
| 2368 |
else: # 3.8 |
| 2369 |
class _UnpackAlias(typing._GenericAlias, _root=True): |
| 2370 |
__class__ = typing.TypeVar |
| 2371 |
|
| 2372 |
class _UnpackForm(_ExtensionsSpecialForm, _root=True): |
| 2373 |
def __getitem__(self, parameters): |
| 2374 |
item = typing._type_check(parameters, |
| 2375 |
f'{self._name} accepts only a single type.') |
| 2376 |
return _UnpackAlias(self, (item,)) |
| 2377 |
|
| 2378 |
Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC) |
| 2379 |
|
| 2380 |
def _is_unpack(obj): |
| 2381 |
return isinstance(obj, _UnpackAlias) |
| 2382 |
|
| 2383 |
|
| 2384 |
if _PEP_696_IMPLEMENTED: |
| 2385 |
from typing import TypeVarTuple |
| 2386 |
|
| 2387 |
elif hasattr(typing, "TypeVarTuple"): # 3.11+ |
| 2388 |
|
| 2389 |
def _unpack_args(*args): |
| 2390 |
newargs = [] |
| 2391 |
for arg in args: |
| 2392 |
subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) |
| 2393 |
if subargs is not None and not (subargs and subargs[-1] is ...): |
| 2394 |
newargs.extend(subargs) |
| 2395 |
else: |
| 2396 |
newargs.append(arg) |
| 2397 |
return newargs |
| 2398 |
|
| 2399 |
# Add default parameter - PEP 696 |
| 2400 |
class TypeVarTuple(metaclass=_TypeVarLikeMeta): |
| 2401 |
"""Type variable tuple.""" |
| 2402 |
|
| 2403 |
_backported_typevarlike = typing.TypeVarTuple |
| 2404 |
|
| 2405 |
def __new__(cls, name, *, default=NoDefault): |
| 2406 |
tvt = typing.TypeVarTuple(name) |
| 2407 |
_set_default(tvt, default) |
| 2408 |
_set_module(tvt) |
| 2409 |
|
| 2410 |
def _typevartuple_prepare_subst(alias, args): |
| 2411 |
params = alias.__parameters__ |
| 2412 |
typevartuple_index = params.index(tvt) |
| 2413 |
for param in params[typevartuple_index + 1:]: |
| 2414 |
if isinstance(param, TypeVarTuple): |
| 2415 |
raise TypeError( |
| 2416 |
f"More than one TypeVarTuple parameter in {alias}" |
| 2417 |
) |
| 2418 |
|
| 2419 |
alen = len(args) |
| 2420 |
plen = len(params) |
| 2421 |
left = typevartuple_index |
| 2422 |
right = plen - typevartuple_index - 1 |
| 2423 |
var_tuple_index = None |
| 2424 |
fillarg = None |
| 2425 |
for k, arg in enumerate(args): |
| 2426 |
if not isinstance(arg, type): |
| 2427 |
subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) |
| 2428 |
if subargs and len(subargs) == 2 and subargs[-1] is ...: |
| 2429 |
if var_tuple_index is not None: |
| 2430 |
raise TypeError( |
| 2431 |
"More than one unpacked " |
| 2432 |
"arbitrary-length tuple argument" |
| 2433 |
) |
| 2434 |
var_tuple_index = k |
| 2435 |
fillarg = subargs[0] |
| 2436 |
if var_tuple_index is not None: |
| 2437 |
left = min(left, var_tuple_index) |
| 2438 |
right = min(right, alen - var_tuple_index - 1) |
| 2439 |
elif left + right > alen: |
| 2440 |
raise TypeError(f"Too few arguments for {alias};" |
| 2441 |
f" actual {alen}, expected at least {plen - 1}") |
| 2442 |
if left == alen - right and tvt.has_default(): |
| 2443 |
replacement = _unpack_args(tvt.__default__) |
| 2444 |
else: |
| 2445 |
replacement = args[left: alen - right] |
| 2446 |
|
| 2447 |
return ( |
| 2448 |
*args[:left], |
| 2449 |
*([fillarg] * (typevartuple_index - left)), |
| 2450 |
replacement, |
| 2451 |
*([fillarg] * (plen - right - left - typevartuple_index - 1)), |
| 2452 |
*args[alen - right:], |
| 2453 |
) |
| 2454 |
|
| 2455 |
tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst |
| 2456 |
return tvt |
| 2457 |
|
| 2458 |
def __init_subclass__(self, *args, **kwds): |
| 2459 |
raise TypeError("Cannot subclass special typing classes") |
| 2460 |
|
| 2461 |
else: # <=3.10 |
| 2462 |
class TypeVarTuple(_DefaultMixin): |
| 2463 |
"""Type variable tuple. |
| 2464 |
|
| 2465 |
Usage:: |
| 2466 |
|
| 2467 |
Ts = TypeVarTuple('Ts') |
| 2468 |
|
| 2469 |
In the same way that a normal type variable is a stand-in for a single |
| 2470 |
type such as ``int``, a type variable *tuple* is a stand-in for a *tuple* |
| 2471 |
type such as ``Tuple[int, str]``. |
| 2472 |
|
| 2473 |
Type variable tuples can be used in ``Generic`` declarations. |
| 2474 |
Consider the following example:: |
| 2475 |
|
| 2476 |
class Array(Generic[*Ts]): ... |
| 2477 |
|
| 2478 |
The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``, |
| 2479 |
where ``T1`` and ``T2`` are type variables. To use these type variables |
| 2480 |
as type parameters of ``Array``, we must *unpack* the type variable tuple using |
| 2481 |
the star operator: ``*Ts``. The signature of ``Array`` then behaves |
| 2482 |
as if we had simply written ``class Array(Generic[T1, T2]): ...``. |
| 2483 |
In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows |
| 2484 |
us to parameterise the class with an *arbitrary* number of type parameters. |
| 2485 |
|
| 2486 |
Type variable tuples can be used anywhere a normal ``TypeVar`` can. |
| 2487 |
This includes class definitions, as shown above, as well as function |
| 2488 |
signatures and variable annotations:: |
| 2489 |
|
| 2490 |
class Array(Generic[*Ts]): |
| 2491 |
|
| 2492 |
def __init__(self, shape: Tuple[*Ts]): |
| 2493 |
self._shape: Tuple[*Ts] = shape |
| 2494 |
|
| 2495 |
def get_shape(self) -> Tuple[*Ts]: |
| 2496 |
return self._shape |
| 2497 |
|
| 2498 |
shape = (Height(480), Width(640)) |
| 2499 |
x: Array[Height, Width] = Array(shape) |
| 2500 |
y = abs(x) # Inferred type is Array[Height, Width] |
| 2501 |
z = x + x # ... is Array[Height, Width] |
| 2502 |
x.get_shape() # ... is tuple[Height, Width] |
| 2503 |
|
| 2504 |
""" |
| 2505 |
|
| 2506 |
# Trick Generic __parameters__. |
| 2507 |
__class__ = typing.TypeVar |
| 2508 |
|
| 2509 |
def __iter__(self): |
| 2510 |
yield self.__unpacked__ |
| 2511 |
|
| 2512 |
def __init__(self, name, *, default=NoDefault): |
| 2513 |
self.__name__ = name |
| 2514 |
_DefaultMixin.__init__(self, default) |
| 2515 |
|
| 2516 |
# for pickling: |
| 2517 |
def_mod = _caller() |
| 2518 |
if def_mod != 'typing_extensions': |
| 2519 |
self.__module__ = def_mod |
| 2520 |
|
| 2521 |
self.__unpacked__ = Unpack[self] |
| 2522 |
|
| 2523 |
def __repr__(self): |
| 2524 |
return self.__name__ |
| 2525 |
|
| 2526 |
def __hash__(self): |
| 2527 |
return object.__hash__(self) |
| 2528 |
|
| 2529 |
def __eq__(self, other): |
| 2530 |
return self is other |
| 2531 |
|
| 2532 |
def __reduce__(self): |
| 2533 |
return self.__name__ |
| 2534 |
|
| 2535 |
def __init_subclass__(self, *args, **kwds): |
| 2536 |
if '_root' not in kwds: |
| 2537 |
raise TypeError("Cannot subclass special typing classes") |
| 2538 |
|
| 2539 |
|
| 2540 |
if hasattr(typing, "reveal_type"): # 3.11+ |
| 2541 |
reveal_type = typing.reveal_type |
| 2542 |
else: # <=3.10 |
| 2543 |
def reveal_type(obj: T, /) -> T: |
| 2544 |
"""Reveal the inferred type of a variable. |
| 2545 |
|
| 2546 |
When a static type checker encounters a call to ``reveal_type()``, |
| 2547 |
it will emit the inferred type of the argument:: |
| 2548 |
|
| 2549 |
x: int = 1 |
| 2550 |
reveal_type(x) |
| 2551 |
|
| 2552 |
Running a static type checker (e.g., ``mypy``) on this example |
| 2553 |
will produce output similar to 'Revealed type is "builtins.int"'. |
| 2554 |
|
| 2555 |
At runtime, the function prints the runtime type of the |
| 2556 |
argument and returns it unchanged. |
| 2557 |
|
| 2558 |
""" |
| 2559 |
print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr) |
| 2560 |
return obj |
| 2561 |
|
| 2562 |
|
| 2563 |
if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"): # 3.11+ |
| 2564 |
_ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH |
| 2565 |
else: # <=3.10 |
| 2566 |
_ASSERT_NEVER_REPR_MAX_LENGTH = 100 |
| 2567 |
|
| 2568 |
|
| 2569 |
if hasattr(typing, "assert_never"): # 3.11+ |
| 2570 |
assert_never = typing.assert_never |
| 2571 |
else: # <=3.10 |
| 2572 |
def assert_never(arg: Never, /) -> Never: |
| 2573 |
"""Assert to the type checker that a line of code is unreachable. |
| 2574 |
|
| 2575 |
Example:: |
| 2576 |
|
| 2577 |
def int_or_str(arg: int | str) -> None: |
| 2578 |
match arg: |
| 2579 |
case int(): |
| 2580 |
print("It's an int") |
| 2581 |
case str(): |
| 2582 |
print("It's a str") |
| 2583 |
case _: |
| 2584 |
assert_never(arg) |
| 2585 |
|
| 2586 |
If a type checker finds that a call to assert_never() is |
| 2587 |
reachable, it will emit an error. |
| 2588 |
|
| 2589 |
At runtime, this throws an exception when called. |
| 2590 |
|
| 2591 |
""" |
| 2592 |
value = repr(arg) |
| 2593 |
if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH: |
| 2594 |
value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...' |
| 2595 |
raise AssertionError(f"Expected code to be unreachable, but got: {value}") |
| 2596 |
|
| 2597 |
|
| 2598 |
if sys.version_info >= (3, 12): # 3.12+ |
| 2599 |
# dataclass_transform exists in 3.11 but lacks the frozen_default parameter |
| 2600 |
dataclass_transform = typing.dataclass_transform |
| 2601 |
else: # <=3.11 |
| 2602 |
def dataclass_transform( |
| 2603 |
*, |
| 2604 |
eq_default: bool = True, |
| 2605 |
order_default: bool = False, |
| 2606 |
kw_only_default: bool = False, |
| 2607 |
frozen_default: bool = False, |
| 2608 |
field_specifiers: typing.Tuple[ |
| 2609 |
typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]], |
| 2610 |
... |
| 2611 |
] = (), |
| 2612 |
**kwargs: typing.Any, |
| 2613 |
) -> typing.Callable[[T], T]: |
| 2614 |
"""Decorator that marks a function, class, or metaclass as providing |
| 2615 |
dataclass-like behavior. |
| 2616 |
|
| 2617 |
Example: |
| 2618 |
|
| 2619 |
from typing_extensions import dataclass_transform |
| 2620 |
|
| 2621 |
_T = TypeVar("_T") |
| 2622 |
|
| 2623 |
# Used on a decorator function |
| 2624 |
@dataclass_transform() |
| 2625 |
def create_model(cls: type[_T]) -> type[_T]: |
| 2626 |
... |
| 2627 |
return cls |
| 2628 |
|
| 2629 |
@create_model |
| 2630 |
class CustomerModel: |
| 2631 |
id: int |
| 2632 |
name: str |
| 2633 |
|
| 2634 |
# Used on a base class |
| 2635 |
@dataclass_transform() |
| 2636 |
class ModelBase: ... |
| 2637 |
|
| 2638 |
class CustomerModel(ModelBase): |
| 2639 |
id: int |
| 2640 |
name: str |
| 2641 |
|
| 2642 |
# Used on a metaclass |
| 2643 |
@dataclass_transform() |
| 2644 |
class ModelMeta(type): ... |
| 2645 |
|
| 2646 |
class ModelBase(metaclass=ModelMeta): ... |
| 2647 |
|
| 2648 |
class CustomerModel(ModelBase): |
| 2649 |
id: int |
| 2650 |
name: str |
| 2651 |
|
| 2652 |
Each of the ``CustomerModel`` classes defined in this example will now |
| 2653 |
behave similarly to a dataclass created with the ``@dataclasses.dataclass`` |
| 2654 |
decorator. For example, the type checker will synthesize an ``__init__`` |
| 2655 |
method. |
| 2656 |
|
| 2657 |
The arguments to this decorator can be used to customize this behavior: |
| 2658 |
- ``eq_default`` indicates whether the ``eq`` parameter is assumed to be |
| 2659 |
True or False if it is omitted by the caller. |
| 2660 |
- ``order_default`` indicates whether the ``order`` parameter is |
| 2661 |
assumed to be True or False if it is omitted by the caller. |
| 2662 |
- ``kw_only_default`` indicates whether the ``kw_only`` parameter is |
| 2663 |
assumed to be True or False if it is omitted by the caller. |
| 2664 |
- ``frozen_default`` indicates whether the ``frozen`` parameter is |
| 2665 |
assumed to be True or False if it is omitted by the caller. |
| 2666 |
- ``field_specifiers`` specifies a static list of supported classes |
| 2667 |
or functions that describe fields, similar to ``dataclasses.field()``. |
| 2668 |
|
| 2669 |
At runtime, this decorator records its arguments in the |
| 2670 |
``__dataclass_transform__`` attribute on the decorated object. |
| 2671 |
|
| 2672 |
See PEP 681 for details. |
| 2673 |
|
| 2674 |
""" |
| 2675 |
def decorator(cls_or_fn): |
| 2676 |
cls_or_fn.__dataclass_transform__ = { |
| 2677 |
"eq_default": eq_default, |
| 2678 |
"order_default": order_default, |
| 2679 |
"kw_only_default": kw_only_default, |
| 2680 |
"frozen_default": frozen_default, |
| 2681 |
"field_specifiers": field_specifiers, |
| 2682 |
"kwargs": kwargs, |
| 2683 |
} |
| 2684 |
return cls_or_fn |
| 2685 |
return decorator |
| 2686 |
|
| 2687 |
|
| 2688 |
if hasattr(typing, "override"): # 3.12+ |
| 2689 |
override = typing.override |
| 2690 |
else: # <=3.11 |
| 2691 |
_F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any]) |
| 2692 |
|
| 2693 |
def override(arg: _F, /) -> _F: |
| 2694 |
"""Indicate that a method is intended to override a method in a base class. |
| 2695 |
|
| 2696 |
Usage: |
| 2697 |
|
| 2698 |
class Base: |
| 2699 |
def method(self) -> None: |
| 2700 |
pass |
| 2701 |
|
| 2702 |
class Child(Base): |
| 2703 |
@override |
| 2704 |
def method(self) -> None: |
| 2705 |
super().method() |
| 2706 |
|
| 2707 |
When this decorator is applied to a method, the type checker will |
| 2708 |
validate that it overrides a method with the same name on a base class. |
| 2709 |
This helps prevent bugs that may occur when a base class is changed |
| 2710 |
without an equivalent change to a child class. |
| 2711 |
|
| 2712 |
There is no runtime checking of these properties. The decorator |
| 2713 |
sets the ``__override__`` attribute to ``True`` on the decorated object |
| 2714 |
to allow runtime introspection. |
| 2715 |
|
| 2716 |
See PEP 698 for details. |
| 2717 |
|
| 2718 |
""" |
| 2719 |
try: |
| 2720 |
arg.__override__ = True |
| 2721 |
except (AttributeError, TypeError): |
| 2722 |
# Skip the attribute silently if it is not writable. |
| 2723 |
# AttributeError happens if the object has __slots__ or a |
| 2724 |
# read-only property, TypeError if it's a builtin class. |
| 2725 |
pass |
| 2726 |
return arg |
| 2727 |
|
| 2728 |
|
| 2729 |
if hasattr(warnings, "deprecated"): |
| 2730 |
deprecated = warnings.deprecated |
| 2731 |
else: |
| 2732 |
_T = typing.TypeVar("_T") |
| 2733 |
|
| 2734 |
class deprecated: |
| 2735 |
"""Indicate that a class, function or overload is deprecated. |
| 2736 |
|
| 2737 |
When this decorator is applied to an object, the type checker |
| 2738 |
will generate a diagnostic on usage of the deprecated object. |
| 2739 |
|
| 2740 |
Usage: |
| 2741 |
|
| 2742 |
@deprecated("Use B instead") |
| 2743 |
class A: |
| 2744 |
pass |
| 2745 |
|
| 2746 |
@deprecated("Use g instead") |
| 2747 |
def f(): |
| 2748 |
pass |
| 2749 |
|
| 2750 |
@overload |
| 2751 |
@deprecated("int support is deprecated") |
| 2752 |
def g(x: int) -> int: ... |
| 2753 |
@overload |
| 2754 |
def g(x: str) -> int: ... |
| 2755 |
|
| 2756 |
The warning specified by *category* will be emitted at runtime |
| 2757 |
on use of deprecated objects. For functions, that happens on calls; |
| 2758 |
for classes, on instantiation and on creation of subclasses. |
| 2759 |
If the *category* is ``None``, no warning is emitted at runtime. |
| 2760 |
The *stacklevel* determines where the |
| 2761 |
warning is emitted. If it is ``1`` (the default), the warning |
| 2762 |
is emitted at the direct caller of the deprecated object; if it |
| 2763 |
is higher, it is emitted further up the stack. |
| 2764 |
Static type checker behavior is not affected by the *category* |
| 2765 |
and *stacklevel* arguments. |
| 2766 |
|
| 2767 |
The deprecation message passed to the decorator is saved in the |
| 2768 |
``__deprecated__`` attribute on the decorated object. |
| 2769 |
If applied to an overload, the decorator |
| 2770 |
must be after the ``@overload`` decorator for the attribute to |
| 2771 |
exist on the overload as returned by ``get_overloads()``. |
| 2772 |
|
| 2773 |
See PEP 702 for details. |
| 2774 |
|
| 2775 |
""" |
| 2776 |
def __init__( |
| 2777 |
self, |
| 2778 |
message: str, |
| 2779 |
/, |
| 2780 |
*, |
| 2781 |
category: typing.Optional[typing.Type[Warning]] = DeprecationWarning, |
| 2782 |
stacklevel: int = 1, |
| 2783 |
) -> None: |
| 2784 |
if not isinstance(message, str): |
| 2785 |
raise TypeError( |
| 2786 |
"Expected an object of type str for 'message', not " |
| 2787 |
f"{type(message).__name__!r}" |
| 2788 |
) |
| 2789 |
self.message = message |
| 2790 |
self.category = category |
| 2791 |
self.stacklevel = stacklevel |
| 2792 |
|
| 2793 |
def __call__(self, arg: _T, /) -> _T: |
| 2794 |
# Make sure the inner functions created below don't |
| 2795 |
# retain a reference to self. |
| 2796 |
msg = self.message |
| 2797 |
category = self.category |
| 2798 |
stacklevel = self.stacklevel |
| 2799 |
if category is None: |
| 2800 |
arg.__deprecated__ = msg |
| 2801 |
return arg |
| 2802 |
elif isinstance(arg, type): |
| 2803 |
import functools |
| 2804 |
from types import MethodType |
| 2805 |
|
| 2806 |
original_new = arg.__new__ |
| 2807 |
|
| 2808 |
@functools.wraps(original_new) |
| 2809 |
def __new__(cls, *args, **kwargs): |
| 2810 |
if cls is arg: |
| 2811 |
warnings.warn(msg, category=category, stacklevel=stacklevel + 1) |
| 2812 |
if original_new is not object.__new__: |
| 2813 |
return original_new(cls, *args, **kwargs) |
| 2814 |
# Mirrors a similar check in object.__new__. |
| 2815 |
elif cls.__init__ is object.__init__ and (args or kwargs): |
| 2816 |
raise TypeError(f"{cls.__name__}() takes no arguments") |
| 2817 |
else: |
| 2818 |
return original_new(cls) |
| 2819 |
|
| 2820 |
arg.__new__ = staticmethod(__new__) |
| 2821 |
|
| 2822 |
original_init_subclass = arg.__init_subclass__ |
| 2823 |
# We need slightly different behavior if __init_subclass__ |
| 2824 |
# is a bound method (likely if it was implemented in Python) |
| 2825 |
if isinstance(original_init_subclass, MethodType): |
| 2826 |
original_init_subclass = original_init_subclass.__func__ |
| 2827 |
|
| 2828 |
@functools.wraps(original_init_subclass) |
| 2829 |
def __init_subclass__(*args, **kwargs): |
| 2830 |
warnings.warn(msg, category=category, stacklevel=stacklevel + 1) |
| 2831 |
return original_init_subclass(*args, **kwargs) |
| 2832 |
|
| 2833 |
arg.__init_subclass__ = classmethod(__init_subclass__) |
| 2834 |
# Or otherwise, which likely means it's a builtin such as |
| 2835 |
# object's implementation of __init_subclass__. |
| 2836 |
else: |
| 2837 |
@functools.wraps(original_init_subclass) |
| 2838 |
def __init_subclass__(*args, **kwargs): |
| 2839 |
warnings.warn(msg, category=category, stacklevel=stacklevel + 1) |
| 2840 |
return original_init_subclass(*args, **kwargs) |
| 2841 |
|
| 2842 |
arg.__init_subclass__ = __init_subclass__ |
| 2843 |
|
| 2844 |
arg.__deprecated__ = __new__.__deprecated__ = msg |
| 2845 |
__init_subclass__.__deprecated__ = msg |
| 2846 |
return arg |
| 2847 |
elif callable(arg): |
| 2848 |
import functools |
| 2849 |
|
| 2850 |
@functools.wraps(arg) |
| 2851 |
def wrapper(*args, **kwargs): |
| 2852 |
warnings.warn(msg, category=category, stacklevel=stacklevel + 1) |
| 2853 |
return arg(*args, **kwargs) |
| 2854 |
|
| 2855 |
arg.__deprecated__ = wrapper.__deprecated__ = msg |
| 2856 |
return wrapper |
| 2857 |
else: |
| 2858 |
raise TypeError( |
| 2859 |
"@deprecated decorator with non-None category must be applied to " |
| 2860 |
f"a class or callable, not {arg!r}" |
| 2861 |
) |
| 2862 |
|
| 2863 |
|
| 2864 |
# We have to do some monkey patching to deal with the dual nature of |
| 2865 |
# Unpack/TypeVarTuple: |
| 2866 |
# - We want Unpack to be a kind of TypeVar so it gets accepted in |
| 2867 |
# Generic[Unpack[Ts]] |
| 2868 |
# - We want it to *not* be treated as a TypeVar for the purposes of |
| 2869 |
# counting generic parameters, so that when we subscript a generic, |
| 2870 |
# the runtime doesn't try to substitute the Unpack with the subscripted type. |
| 2871 |
if not hasattr(typing, "TypeVarTuple"): |
| 2872 |
def _check_generic(cls, parameters, elen=_marker): |
| 2873 |
"""Check correct count for parameters of a generic cls (internal helper). |
| 2874 |
|
| 2875 |
This gives a nice error message in case of count mismatch. |
| 2876 |
""" |
| 2877 |
if not elen: |
| 2878 |
raise TypeError(f"{cls} is not a generic class") |
| 2879 |
if elen is _marker: |
| 2880 |
if not hasattr(cls, "__parameters__") or not cls.__parameters__: |
| 2881 |
raise TypeError(f"{cls} is not a generic class") |
| 2882 |
elen = len(cls.__parameters__) |
| 2883 |
alen = len(parameters) |
| 2884 |
if alen != elen: |
| 2885 |
expect_val = elen |
| 2886 |
if hasattr(cls, "__parameters__"): |
| 2887 |
parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] |
| 2888 |
num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters) |
| 2889 |
if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples): |
| 2890 |
return |
| 2891 |
|
| 2892 |
# deal with TypeVarLike defaults |
| 2893 |
# required TypeVarLikes cannot appear after a defaulted one. |
| 2894 |
if alen < elen: |
| 2895 |
# since we validate TypeVarLike default in _collect_type_vars |
| 2896 |
# or _collect_parameters we can safely check parameters[alen] |
| 2897 |
if ( |
| 2898 |
getattr(parameters[alen], '__default__', NoDefault) |
| 2899 |
is not NoDefault |
| 2900 |
): |
| 2901 |
return |
| 2902 |
|
| 2903 |
num_default_tv = sum(getattr(p, '__default__', NoDefault) |
| 2904 |
is not NoDefault for p in parameters) |
| 2905 |
|
| 2906 |
elen -= num_default_tv |
| 2907 |
|
| 2908 |
expect_val = f"at least {elen}" |
| 2909 |
|
| 2910 |
things = "arguments" if sys.version_info >= (3, 10) else "parameters" |
| 2911 |
raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}" |
| 2912 |
f" for {cls}; actual {alen}, expected {expect_val}") |
| 2913 |
else: |
| 2914 |
# Python 3.11+ |
| 2915 |
|
| 2916 |
def _check_generic(cls, parameters, elen): |
| 2917 |
"""Check correct count for parameters of a generic cls (internal helper). |
| 2918 |
|
| 2919 |
This gives a nice error message in case of count mismatch. |
| 2920 |
""" |
| 2921 |
if not elen: |
| 2922 |
raise TypeError(f"{cls} is not a generic class") |
| 2923 |
alen = len(parameters) |
| 2924 |
if alen != elen: |
| 2925 |
expect_val = elen |
| 2926 |
if hasattr(cls, "__parameters__"): |
| 2927 |
parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] |
| 2928 |
|
| 2929 |
# deal with TypeVarLike defaults |
| 2930 |
# required TypeVarLikes cannot appear after a defaulted one. |
| 2931 |
if alen < elen: |
| 2932 |
# since we validate TypeVarLike default in _collect_type_vars |
| 2933 |
# or _collect_parameters we can safely check parameters[alen] |
| 2934 |
if ( |
| 2935 |
getattr(parameters[alen], '__default__', NoDefault) |
| 2936 |
is not NoDefault |
| 2937 |
): |
| 2938 |
return |
| 2939 |
|
| 2940 |
num_default_tv = sum(getattr(p, '__default__', NoDefault) |
| 2941 |
is not NoDefault for p in parameters) |
| 2942 |
|
| 2943 |
elen -= num_default_tv |
| 2944 |
|
| 2945 |
expect_val = f"at least {elen}" |
| 2946 |
|
| 2947 |
raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments" |
| 2948 |
f" for {cls}; actual {alen}, expected {expect_val}") |
| 2949 |
|
| 2950 |
if not _PEP_696_IMPLEMENTED: |
| 2951 |
typing._check_generic = _check_generic |
| 2952 |
|
| 2953 |
|
| 2954 |
def _has_generic_or_protocol_as_origin() -> bool: |
| 2955 |
try: |
| 2956 |
frame = sys._getframe(2) |
| 2957 |
# - Catch AttributeError: not all Python implementations have sys._getframe() |
| 2958 |
# - Catch ValueError: maybe we're called from an unexpected module |
| 2959 |
# and the call stack isn't deep enough |
| 2960 |
except (AttributeError, ValueError): |
| 2961 |
return False # err on the side of leniency |
| 2962 |
else: |
| 2963 |
# If we somehow get invoked from outside typing.py, |
| 2964 |
# also err on the side of leniency |
| 2965 |
if frame.f_globals.get("__name__") != "typing": |
| 2966 |
return False |
| 2967 |
origin = frame.f_locals.get("origin") |
| 2968 |
# Cannot use "in" because origin may be an object with a buggy __eq__ that |
| 2969 |
# throws an error. |
| 2970 |
return origin is typing.Generic or origin is Protocol or origin is typing.Protocol |
| 2971 |
|
| 2972 |
|
| 2973 |
_TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)} |
| 2974 |
|
| 2975 |
|
| 2976 |
def _is_unpacked_typevartuple(x) -> bool: |
| 2977 |
if get_origin(x) is not Unpack: |
| 2978 |
return False |
| 2979 |
args = get_args(x) |
| 2980 |
return ( |
| 2981 |
bool(args) |
| 2982 |
and len(args) == 1 |
| 2983 |
and type(args[0]) in _TYPEVARTUPLE_TYPES |
| 2984 |
) |
| 2985 |
|
| 2986 |
|
| 2987 |
# Python 3.11+ _collect_type_vars was renamed to _collect_parameters |
| 2988 |
if hasattr(typing, '_collect_type_vars'): |
| 2989 |
def _collect_type_vars(types, typevar_types=None): |
| 2990 |
"""Collect all type variable contained in types in order of |
| 2991 |
first appearance (lexicographic order). For example:: |
| 2992 |
|
| 2993 |
_collect_type_vars((T, List[S, T])) == (T, S) |
| 2994 |
""" |
| 2995 |
if typevar_types is None: |
| 2996 |
typevar_types = typing.TypeVar |
| 2997 |
tvars = [] |
| 2998 |
|
| 2999 |
# A required TypeVarLike cannot appear after a TypeVarLike with a default |
| 3000 |
# if it was a direct call to `Generic[]` or `Protocol[]` |
| 3001 |
enforce_default_ordering = _has_generic_or_protocol_as_origin() |
| 3002 |
default_encountered = False |
| 3003 |
|
| 3004 |
# Also, a TypeVarLike with a default cannot appear after a TypeVarTuple |
| 3005 |
type_var_tuple_encountered = False |
| 3006 |
|
| 3007 |
for t in types: |
| 3008 |
if _is_unpacked_typevartuple(t): |
| 3009 |
type_var_tuple_encountered = True |
| 3010 |
elif isinstance(t, typevar_types) and t not in tvars: |
| 3011 |
if enforce_default_ordering: |
| 3012 |
has_default = getattr(t, '__default__', NoDefault) is not NoDefault |
| 3013 |
if has_default: |
| 3014 |
if type_var_tuple_encountered: |
| 3015 |
raise TypeError('Type parameter with a default' |
| 3016 |
' follows TypeVarTuple') |
| 3017 |
default_encountered = True |
| 3018 |
elif default_encountered: |
| 3019 |
raise TypeError(f'Type parameter {t!r} without a default' |
| 3020 |
' follows type parameter with a default') |
| 3021 |
|
| 3022 |
tvars.append(t) |
| 3023 |
if _should_collect_from_parameters(t): |
| 3024 |
tvars.extend([t for t in t.__parameters__ if t not in tvars]) |
| 3025 |
return tuple(tvars) |
| 3026 |
|
| 3027 |
typing._collect_type_vars = _collect_type_vars |
| 3028 |
else: |
| 3029 |
def _collect_parameters(args): |
| 3030 |
"""Collect all type variables and parameter specifications in args |
| 3031 |
in order of first appearance (lexicographic order). |
| 3032 |
|
| 3033 |
For example:: |
| 3034 |
|
| 3035 |
assert _collect_parameters((T, Callable[P, T])) == (T, P) |
| 3036 |
""" |
| 3037 |
parameters = [] |
| 3038 |
|
| 3039 |
# A required TypeVarLike cannot appear after a TypeVarLike with default |
| 3040 |
# if it was a direct call to `Generic[]` or `Protocol[]` |
| 3041 |
enforce_default_ordering = _has_generic_or_protocol_as_origin() |
| 3042 |
default_encountered = False |
| 3043 |
|
| 3044 |
# Also, a TypeVarLike with a default cannot appear after a TypeVarTuple |
| 3045 |
type_var_tuple_encountered = False |
| 3046 |
|
| 3047 |
for t in args: |
| 3048 |
if isinstance(t, type): |
| 3049 |
# We don't want __parameters__ descriptor of a bare Python class. |
| 3050 |
pass |
| 3051 |
elif isinstance(t, tuple): |
| 3052 |
# `t` might be a tuple, when `ParamSpec` is substituted with |
| 3053 |
# `[T, int]`, or `[int, *Ts]`, etc. |
| 3054 |
for x in t: |
| 3055 |
for collected in _collect_parameters([x]): |
| 3056 |
if collected not in parameters: |
| 3057 |
parameters.append(collected) |
| 3058 |
elif hasattr(t, '__typing_subst__'): |
| 3059 |
if t not in parameters: |
| 3060 |
if enforce_default_ordering: |
| 3061 |
has_default = ( |
| 3062 |
getattr(t, '__default__', NoDefault) is not NoDefault |
| 3063 |
) |
| 3064 |
|
| 3065 |
if type_var_tuple_encountered and has_default: |
| 3066 |
raise TypeError('Type parameter with a default' |
| 3067 |
' follows TypeVarTuple') |
| 3068 |
|
| 3069 |
if has_default: |
| 3070 |
default_encountered = True |
| 3071 |
elif default_encountered: |
| 3072 |
raise TypeError(f'Type parameter {t!r} without a default' |
| 3073 |
' follows type parameter with a default') |
| 3074 |
|
| 3075 |
parameters.append(t) |
| 3076 |
else: |
| 3077 |
if _is_unpacked_typevartuple(t): |
| 3078 |
type_var_tuple_encountered = True |
| 3079 |
for x in getattr(t, '__parameters__', ()): |
| 3080 |
if x not in parameters: |
| 3081 |
parameters.append(x) |
| 3082 |
|
| 3083 |
return tuple(parameters) |
| 3084 |
|
| 3085 |
if not _PEP_696_IMPLEMENTED: |
| 3086 |
typing._collect_parameters = _collect_parameters |
| 3087 |
|
| 3088 |
# Backport typing.NamedTuple as it exists in Python 3.13. |
| 3089 |
# In 3.11, the ability to define generic `NamedTuple`s was supported. |
| 3090 |
# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8. |
| 3091 |
# On 3.12, we added __orig_bases__ to call-based NamedTuples |
| 3092 |
# On 3.13, we deprecated kwargs-based NamedTuples |
| 3093 |
if sys.version_info >= (3, 13): |
| 3094 |
NamedTuple = typing.NamedTuple |
| 3095 |
else: |
| 3096 |
def _make_nmtuple(name, types, module, defaults=()): |
| 3097 |
fields = [n for n, t in types] |
| 3098 |
annotations = {n: typing._type_check(t, f"field {n} annotation must be a type") |
| 3099 |
for n, t in types} |
| 3100 |
nm_tpl = collections.namedtuple(name, fields, |
| 3101 |
defaults=defaults, module=module) |
| 3102 |
nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations |
| 3103 |
# The `_field_types` attribute was removed in 3.9; |
| 3104 |
# in earlier versions, it is the same as the `__annotations__` attribute |
| 3105 |
if sys.version_info < (3, 9): |
| 3106 |
nm_tpl._field_types = annotations |
| 3107 |
return nm_tpl |
| 3108 |
|
| 3109 |
_prohibited_namedtuple_fields = typing._prohibited |
| 3110 |
_special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'}) |
| 3111 |
|
| 3112 |
class _NamedTupleMeta(type): |
| 3113 |
def __new__(cls, typename, bases, ns): |
| 3114 |
assert _NamedTuple in bases |
| 3115 |
for base in bases: |
| 3116 |
if base is not _NamedTuple and base is not typing.Generic: |
| 3117 |
raise TypeError( |
| 3118 |
'can only inherit from a NamedTuple type and Generic') |
| 3119 |
bases = tuple(tuple if base is _NamedTuple else base for base in bases) |
| 3120 |
if "__annotations__" in ns: |
| 3121 |
types = ns["__annotations__"] |
| 3122 |
elif "__annotate__" in ns: |
| 3123 |
# TODO: Use inspect.VALUE here, and make the annotations lazily evaluated |
| 3124 |
types = ns["__annotate__"](1) |
| 3125 |
else: |
| 3126 |
types = {} |
| 3127 |
default_names = [] |
| 3128 |
for field_name in types: |
| 3129 |
if field_name in ns: |
| 3130 |
default_names.append(field_name) |
| 3131 |
elif default_names: |
| 3132 |
raise TypeError(f"Non-default namedtuple field {field_name} " |
| 3133 |
f"cannot follow default field" |
| 3134 |
f"{'s' if len(default_names) > 1 else ''} " |
| 3135 |
f"{', '.join(default_names)}") |
| 3136 |
nm_tpl = _make_nmtuple( |
| 3137 |
typename, types.items(), |
| 3138 |
defaults=[ns[n] for n in default_names], |
| 3139 |
module=ns['__module__'] |
| 3140 |
) |
| 3141 |
nm_tpl.__bases__ = bases |
| 3142 |
if typing.Generic in bases: |
| 3143 |
if hasattr(typing, '_generic_class_getitem'): # 3.12+ |
| 3144 |
nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem) |
| 3145 |
else: |
| 3146 |
class_getitem = typing.Generic.__class_getitem__.__func__ |
| 3147 |
nm_tpl.__class_getitem__ = classmethod(class_getitem) |
| 3148 |
# update from user namespace without overriding special namedtuple attributes |
| 3149 |
for key, val in ns.items(): |
| 3150 |
if key in _prohibited_namedtuple_fields: |
| 3151 |
raise AttributeError("Cannot overwrite NamedTuple attribute " + key) |
| 3152 |
elif key not in _special_namedtuple_fields: |
| 3153 |
if key not in nm_tpl._fields: |
| 3154 |
setattr(nm_tpl, key, ns[key]) |
| 3155 |
try: |
| 3156 |
set_name = type(val).__set_name__ |
| 3157 |
except AttributeError: |
| 3158 |
pass |
| 3159 |
else: |
| 3160 |
try: |
| 3161 |
set_name(val, nm_tpl, key) |
| 3162 |
except BaseException as e: |
| 3163 |
msg = ( |
| 3164 |
f"Error calling __set_name__ on {type(val).__name__!r} " |
| 3165 |
f"instance {key!r} in {typename!r}" |
| 3166 |
) |
| 3167 |
# BaseException.add_note() existed on py311, |
| 3168 |
# but the __set_name__ machinery didn't start |
| 3169 |
# using add_note() until py312. |
| 3170 |
# Making sure exceptions are raised in the same way |
| 3171 |
# as in "normal" classes seems most important here. |
| 3172 |
if sys.version_info >= (3, 12): |
| 3173 |
e.add_note(msg) |
| 3174 |
raise |
| 3175 |
else: |
| 3176 |
raise RuntimeError(msg) from e |
| 3177 |
|
| 3178 |
if typing.Generic in bases: |
| 3179 |
nm_tpl.__init_subclass__() |
| 3180 |
return nm_tpl |
| 3181 |
|
| 3182 |
_NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {}) |
| 3183 |
|
| 3184 |
def _namedtuple_mro_entries(bases): |
| 3185 |
assert NamedTuple in bases |
| 3186 |
return (_NamedTuple,) |
| 3187 |
|
| 3188 |
@_ensure_subclassable(_namedtuple_mro_entries) |
| 3189 |
def NamedTuple(typename, fields=_marker, /, **kwargs): |
| 3190 |
"""Typed version of namedtuple. |
| 3191 |
|
| 3192 |
Usage:: |
| 3193 |
|
| 3194 |
class Employee(NamedTuple): |
| 3195 |
name: str |
| 3196 |
id: int |
| 3197 |
|
| 3198 |
This is equivalent to:: |
| 3199 |
|
| 3200 |
Employee = collections.namedtuple('Employee', ['name', 'id']) |
| 3201 |
|
| 3202 |
The resulting class has an extra __annotations__ attribute, giving a |
| 3203 |
dict that maps field names to types. (The field names are also in |
| 3204 |
the _fields attribute, which is part of the namedtuple API.) |
| 3205 |
An alternative equivalent functional syntax is also accepted:: |
| 3206 |
|
| 3207 |
Employee = NamedTuple('Employee', [('name', str), ('id', int)]) |
| 3208 |
""" |
| 3209 |
if fields is _marker: |
| 3210 |
if kwargs: |
| 3211 |
deprecated_thing = "Creating NamedTuple classes using keyword arguments" |
| 3212 |
deprecation_msg = ( |
| 3213 |
"{name} is deprecated and will be disallowed in Python {remove}. " |
| 3214 |
"Use the class-based or functional syntax instead." |
| 3215 |
) |
| 3216 |
else: |
| 3217 |
deprecated_thing = "Failing to pass a value for the 'fields' parameter" |
| 3218 |
example = f"`{typename} = NamedTuple({typename!r}, [])`" |
| 3219 |
deprecation_msg = ( |
| 3220 |
"{name} is deprecated and will be disallowed in Python {remove}. " |
| 3221 |
"To create a NamedTuple class with 0 fields " |
| 3222 |
"using the functional syntax, " |
| 3223 |
"pass an empty list, e.g. " |
| 3224 |
) + example + "." |
| 3225 |
elif fields is None: |
| 3226 |
if kwargs: |
| 3227 |
raise TypeError( |
| 3228 |
"Cannot pass `None` as the 'fields' parameter " |
| 3229 |
"and also specify fields using keyword arguments" |
| 3230 |
) |
| 3231 |
else: |
| 3232 |
deprecated_thing = "Passing `None` as the 'fields' parameter" |
| 3233 |
example = f"`{typename} = NamedTuple({typename!r}, [])`" |
| 3234 |
deprecation_msg = ( |
| 3235 |
"{name} is deprecated and will be disallowed in Python {remove}. " |
| 3236 |
"To create a NamedTuple class with 0 fields " |
| 3237 |
"using the functional syntax, " |
| 3238 |
"pass an empty list, e.g. " |
| 3239 |
) + example + "." |
| 3240 |
elif kwargs: |
| 3241 |
raise TypeError("Either list of fields or keywords" |
| 3242 |
" can be provided to NamedTuple, not both") |
| 3243 |
if fields is _marker or fields is None: |
| 3244 |
warnings.warn( |
| 3245 |
deprecation_msg.format(name=deprecated_thing, remove="3.15"), |
| 3246 |
DeprecationWarning, |
| 3247 |
stacklevel=2, |
| 3248 |
) |
| 3249 |
fields = kwargs.items() |
| 3250 |
nt = _make_nmtuple(typename, fields, module=_caller()) |
| 3251 |
nt.__orig_bases__ = (NamedTuple,) |
| 3252 |
return nt |
| 3253 |
|
| 3254 |
|
| 3255 |
if hasattr(collections.abc, "Buffer"): |
| 3256 |
Buffer = collections.abc.Buffer |
| 3257 |
else: |
| 3258 |
class Buffer(abc.ABC): # noqa: B024 |
| 3259 |
"""Base class for classes that implement the buffer protocol. |
| 3260 |
|
| 3261 |
The buffer protocol allows Python objects to expose a low-level |
| 3262 |
memory buffer interface. Before Python 3.12, it is not possible |
| 3263 |
to implement the buffer protocol in pure Python code, or even |
| 3264 |
to check whether a class implements the buffer protocol. In |
| 3265 |
Python 3.12 and higher, the ``__buffer__`` method allows access |
| 3266 |
to the buffer protocol from Python code, and the |
| 3267 |
``collections.abc.Buffer`` ABC allows checking whether a class |
| 3268 |
implements the buffer protocol. |
| 3269 |
|
| 3270 |
To indicate support for the buffer protocol in earlier versions, |
| 3271 |
inherit from this ABC, either in a stub file or at runtime, |
| 3272 |
or use ABC registration. This ABC provides no methods, because |
| 3273 |
there is no Python-accessible methods shared by pre-3.12 buffer |
| 3274 |
classes. It is useful primarily for static checks. |
| 3275 |
|
| 3276 |
""" |
| 3277 |
|
| 3278 |
# As a courtesy, register the most common stdlib buffer classes. |
| 3279 |
Buffer.register(memoryview) |
| 3280 |
Buffer.register(bytearray) |
| 3281 |
Buffer.register(bytes) |
| 3282 |
|
| 3283 |
|
| 3284 |
# Backport of types.get_original_bases, available on 3.12+ in CPython |
| 3285 |
if hasattr(_types, "get_original_bases"): |
| 3286 |
get_original_bases = _types.get_original_bases |
| 3287 |
else: |
| 3288 |
def get_original_bases(cls, /): |
| 3289 |
"""Return the class's "original" bases prior to modification by `__mro_entries__`. |
| 3290 |
|
| 3291 |
Examples:: |
| 3292 |
|
| 3293 |
from typing import TypeVar, Generic |
| 3294 |
from typing_extensions import NamedTuple, TypedDict |
| 3295 |
|
| 3296 |
T = TypeVar("T") |
| 3297 |
class Foo(Generic[T]): ... |
| 3298 |
class Bar(Foo[int], float): ... |
| 3299 |
class Baz(list[str]): ... |
| 3300 |
Eggs = NamedTuple("Eggs", [("a", int), ("b", str)]) |
| 3301 |
Spam = TypedDict("Spam", {"a": int, "b": str}) |
| 3302 |
|
| 3303 |
assert get_original_bases(Bar) == (Foo[int], float) |
| 3304 |
assert get_original_bases(Baz) == (list[str],) |
| 3305 |
assert get_original_bases(Eggs) == (NamedTuple,) |
| 3306 |
assert get_original_bases(Spam) == (TypedDict,) |
| 3307 |
assert get_original_bases(int) == (object,) |
| 3308 |
""" |
| 3309 |
try: |
| 3310 |
return cls.__dict__.get("__orig_bases__", cls.__bases__) |
| 3311 |
except AttributeError: |
| 3312 |
raise TypeError( |
| 3313 |
f'Expected an instance of type, not {type(cls).__name__!r}' |
| 3314 |
) from None |
| 3315 |
|
| 3316 |
|
| 3317 |
# NewType is a class on Python 3.10+, making it pickleable |
| 3318 |
# The error message for subclassing instances of NewType was improved on 3.11+ |
| 3319 |
if sys.version_info >= (3, 11): |
| 3320 |
NewType = typing.NewType |
| 3321 |
else: |
| 3322 |
class NewType: |
| 3323 |
"""NewType creates simple unique types with almost zero |
| 3324 |
runtime overhead. NewType(name, tp) is considered a subtype of tp |
| 3325 |
by static type checkers. At runtime, NewType(name, tp) returns |
| 3326 |
a dummy callable that simply returns its argument. Usage:: |
| 3327 |
UserId = NewType('UserId', int) |
| 3328 |
def name_by_id(user_id: UserId) -> str: |
| 3329 |
... |
| 3330 |
UserId('user') # Fails type check |
| 3331 |
name_by_id(42) # Fails type check |
| 3332 |
name_by_id(UserId(42)) # OK |
| 3333 |
num = UserId(5) + 1 # type: int |
| 3334 |
""" |
| 3335 |
|
| 3336 |
def __call__(self, obj, /): |
| 3337 |
return obj |
| 3338 |
|
| 3339 |
def __init__(self, name, tp): |
| 3340 |
self.__qualname__ = name |
| 3341 |
if '.' in name: |
| 3342 |
name = name.rpartition('.')[-1] |
| 3343 |
self.__name__ = name |
| 3344 |
self.__supertype__ = tp |
| 3345 |
def_mod = _caller() |
| 3346 |
if def_mod != 'typing_extensions': |
| 3347 |
self.__module__ = def_mod |
| 3348 |
|
| 3349 |
def __mro_entries__(self, bases): |
| 3350 |
# We defined __mro_entries__ to get a better error message |
| 3351 |
# if a user attempts to subclass a NewType instance. bpo-46170 |
| 3352 |
supercls_name = self.__name__ |
| 3353 |
|
| 3354 |
class Dummy: |
| 3355 |
def __init_subclass__(cls): |
| 3356 |
subcls_name = cls.__name__ |
| 3357 |
raise TypeError( |
| 3358 |
f"Cannot subclass an instance of NewType. " |
| 3359 |
f"Perhaps you were looking for: " |
| 3360 |
f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`" |
| 3361 |
) |
| 3362 |
|
| 3363 |
return (Dummy,) |
| 3364 |
|
| 3365 |
def __repr__(self): |
| 3366 |
return f'{self.__module__}.{self.__qualname__}' |
| 3367 |
|
| 3368 |
def __reduce__(self): |
| 3369 |
return self.__qualname__ |
| 3370 |
|
| 3371 |
if sys.version_info >= (3, 10): |
| 3372 |
# PEP 604 methods |
| 3373 |
# It doesn't make sense to have these methods on Python <3.10 |
| 3374 |
|
| 3375 |
def __or__(self, other): |
| 3376 |
return typing.Union[self, other] |
| 3377 |
|
| 3378 |
def __ror__(self, other): |
| 3379 |
return typing.Union[other, self] |
| 3380 |
|
| 3381 |
|
| 3382 |
if hasattr(typing, "TypeAliasType"): |
| 3383 |
TypeAliasType = typing.TypeAliasType |
| 3384 |
else: |
| 3385 |
def _is_unionable(obj): |
| 3386 |
"""Corresponds to is_unionable() in unionobject.c in CPython.""" |
| 3387 |
return obj is None or isinstance(obj, ( |
| 3388 |
type, |
| 3389 |
_types.GenericAlias, |
| 3390 |
_types.UnionType, |
| 3391 |
TypeAliasType, |
| 3392 |
)) |
| 3393 |
|
| 3394 |
class TypeAliasType: |
| 3395 |
"""Create named, parameterized type aliases. |
| 3396 |
|
| 3397 |
This provides a backport of the new `type` statement in Python 3.12: |
| 3398 |
|
| 3399 |
type ListOrSet[T] = list[T] | set[T] |
| 3400 |
|
| 3401 |
is equivalent to: |
| 3402 |
|
| 3403 |
T = TypeVar("T") |
| 3404 |
ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,)) |
| 3405 |
|
| 3406 |
The name ListOrSet can then be used as an alias for the type it refers to. |
| 3407 |
|
| 3408 |
The type_params argument should contain all the type parameters used |
| 3409 |
in the value of the type alias. If the alias is not generic, this |
| 3410 |
argument is omitted. |
| 3411 |
|
| 3412 |
Static type checkers should only support type aliases declared using |
| 3413 |
TypeAliasType that follow these rules: |
| 3414 |
|
| 3415 |
- The first argument (the name) must be a string literal. |
| 3416 |
- The TypeAliasType instance must be immediately assigned to a variable |
| 3417 |
of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid, |
| 3418 |
as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)'). |
| 3419 |
|
| 3420 |
""" |
| 3421 |
|
| 3422 |
def __init__(self, name: str, value, *, type_params=()): |
| 3423 |
if not isinstance(name, str): |
| 3424 |
raise TypeError("TypeAliasType name must be a string") |
| 3425 |
self.__value__ = value |
| 3426 |
self.__type_params__ = type_params |
| 3427 |
|
| 3428 |
parameters = [] |
| 3429 |
for type_param in type_params: |
| 3430 |
if isinstance(type_param, TypeVarTuple): |
| 3431 |
parameters.extend(type_param) |
| 3432 |
else: |
| 3433 |
parameters.append(type_param) |
| 3434 |
self.__parameters__ = tuple(parameters) |
| 3435 |
def_mod = _caller() |
| 3436 |
if def_mod != 'typing_extensions': |
| 3437 |
self.__module__ = def_mod |
| 3438 |
# Setting this attribute closes the TypeAliasType from further modification |
| 3439 |
self.__name__ = name |
| 3440 |
|
| 3441 |
def __setattr__(self, name: str, value: object, /) -> None: |
| 3442 |
if hasattr(self, "__name__"): |
| 3443 |
self._raise_attribute_error(name) |
| 3444 |
super().__setattr__(name, value) |
| 3445 |
|
| 3446 |
def __delattr__(self, name: str, /) -> Never: |
| 3447 |
self._raise_attribute_error(name) |
| 3448 |
|
| 3449 |
def _raise_attribute_error(self, name: str) -> Never: |
| 3450 |
# Match the Python 3.12 error messages exactly |
| 3451 |
if name == "__name__": |
| 3452 |
raise AttributeError("readonly attribute") |
| 3453 |
elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}: |
| 3454 |
raise AttributeError( |
| 3455 |
f"attribute '{name}' of 'typing.TypeAliasType' objects " |
| 3456 |
"is not writable" |
| 3457 |
) |
| 3458 |
else: |
| 3459 |
raise AttributeError( |
| 3460 |
f"'typing.TypeAliasType' object has no attribute '{name}'" |
| 3461 |
) |
| 3462 |
|
| 3463 |
def __repr__(self) -> str: |
| 3464 |
return self.__name__ |
| 3465 |
|
| 3466 |
def __getitem__(self, parameters): |
| 3467 |
if not isinstance(parameters, tuple): |
| 3468 |
parameters = (parameters,) |
| 3469 |
parameters = [ |
| 3470 |
typing._type_check( |
| 3471 |
item, f'Subscripting {self.__name__} requires a type.' |
| 3472 |
) |
| 3473 |
for item in parameters |
| 3474 |
] |
| 3475 |
return typing._GenericAlias(self, tuple(parameters)) |
| 3476 |
|
| 3477 |
def __reduce__(self): |
| 3478 |
return self.__name__ |
| 3479 |
|
| 3480 |
def __init_subclass__(cls, *args, **kwargs): |
| 3481 |
raise TypeError( |
| 3482 |
"type 'typing_extensions.TypeAliasType' is not an acceptable base type" |
| 3483 |
) |
| 3484 |
|
| 3485 |
# The presence of this method convinces typing._type_check |
| 3486 |
# that TypeAliasTypes are types. |
| 3487 |
def __call__(self): |
| 3488 |
raise TypeError("Type alias is not callable") |
| 3489 |
|
| 3490 |
if sys.version_info >= (3, 10): |
| 3491 |
def __or__(self, right): |
| 3492 |
# For forward compatibility with 3.12, reject Unions |
| 3493 |
# that are not accepted by the built-in Union. |
| 3494 |
if not _is_unionable(right): |
| 3495 |
return NotImplemented |
| 3496 |
return typing.Union[self, right] |
| 3497 |
|
| 3498 |
def __ror__(self, left): |
| 3499 |
if not _is_unionable(left): |
| 3500 |
return NotImplemented |
| 3501 |
return typing.Union[left, self] |
| 3502 |
|
| 3503 |
|
| 3504 |
if hasattr(typing, "is_protocol"): |
| 3505 |
is_protocol = typing.is_protocol |
| 3506 |
get_protocol_members = typing.get_protocol_members |
| 3507 |
else: |
| 3508 |
def is_protocol(tp: type, /) -> bool: |
| 3509 |
"""Return True if the given type is a Protocol. |
| 3510 |
|
| 3511 |
Example:: |
| 3512 |
|
| 3513 |
>>> from typing_extensions import Protocol, is_protocol |
| 3514 |
>>> class P(Protocol): |
| 3515 |
... def a(self) -> str: ... |
| 3516 |
... b: int |
| 3517 |
>>> is_protocol(P) |
| 3518 |
True |
| 3519 |
>>> is_protocol(int) |
| 3520 |
False |
| 3521 |
""" |
| 3522 |
return ( |
| 3523 |
isinstance(tp, type) |
| 3524 |
and getattr(tp, '_is_protocol', False) |
| 3525 |
and tp is not Protocol |
| 3526 |
and tp is not typing.Protocol |
| 3527 |
) |
| 3528 |
|
| 3529 |
def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]: |
| 3530 |
"""Return the set of members defined in a Protocol. |
| 3531 |
|
| 3532 |
Example:: |
| 3533 |
|
| 3534 |
>>> from typing_extensions import Protocol, get_protocol_members |
| 3535 |
>>> class P(Protocol): |
| 3536 |
... def a(self) -> str: ... |
| 3537 |
... b: int |
| 3538 |
>>> get_protocol_members(P) |
| 3539 |
frozenset({'a', 'b'}) |
| 3540 |
|
| 3541 |
Raise a TypeError for arguments that are not Protocols. |
| 3542 |
""" |
| 3543 |
if not is_protocol(tp): |
| 3544 |
raise TypeError(f'{tp!r} is not a Protocol') |
| 3545 |
if hasattr(tp, '__protocol_attrs__'): |
| 3546 |
return frozenset(tp.__protocol_attrs__) |
| 3547 |
return frozenset(_get_protocol_attrs(tp)) |
| 3548 |
|
| 3549 |
|
| 3550 |
if hasattr(typing, "Doc"): |
| 3551 |
Doc = typing.Doc |
| 3552 |
else: |
| 3553 |
class Doc: |
| 3554 |
"""Define the documentation of a type annotation using ``Annotated``, to be |
| 3555 |
used in class attributes, function and method parameters, return values, |
| 3556 |
and variables. |
| 3557 |
|
| 3558 |
The value should be a positional-only string literal to allow static tools |
| 3559 |
like editors and documentation generators to use it. |
| 3560 |
|
| 3561 |
This complements docstrings. |
| 3562 |
|
| 3563 |
The string value passed is available in the attribute ``documentation``. |
| 3564 |
|
| 3565 |
Example:: |
| 3566 |
|
| 3567 |
>>> from typing_extensions import Annotated, Doc |
| 3568 |
>>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ... |
| 3569 |
""" |
| 3570 |
def __init__(self, documentation: str, /) -> None: |
| 3571 |
self.documentation = documentation |
| 3572 |
|
| 3573 |
def __repr__(self) -> str: |
| 3574 |
return f"Doc({self.documentation!r})" |
| 3575 |
|
| 3576 |
def __hash__(self) -> int: |
| 3577 |
return hash(self.documentation) |
| 3578 |
|
| 3579 |
def __eq__(self, other: object) -> bool: |
| 3580 |
if not isinstance(other, Doc): |
| 3581 |
return NotImplemented |
| 3582 |
return self.documentation == other.documentation |
| 3583 |
|
| 3584 |
|
| 3585 |
_CapsuleType = getattr(_types, "CapsuleType", None) |
| 3586 |
|
| 3587 |
if _CapsuleType is None: |
| 3588 |
try: |
| 3589 |
import _socket |
| 3590 |
except ImportError: |
| 3591 |
pass |
| 3592 |
else: |
| 3593 |
_CAPI = getattr(_socket, "CAPI", None) |
| 3594 |
if _CAPI is not None: |
| 3595 |
_CapsuleType = type(_CAPI) |
| 3596 |
|
| 3597 |
if _CapsuleType is not None: |
| 3598 |
CapsuleType = _CapsuleType |
| 3599 |
__all__.append("CapsuleType") |
| 3600 |
|
| 3601 |
|
| 3602 |
# Aliases for items that have always been in typing. |
| 3603 |
# Explicitly assign these (rather than using `from typing import *` at the top), |
| 3604 |
# so that we get a CI error if one of these is deleted from typing.py |
| 3605 |
# in a future version of Python |
| 3606 |
AbstractSet = typing.AbstractSet |
| 3607 |
AnyStr = typing.AnyStr |
| 3608 |
BinaryIO = typing.BinaryIO |
| 3609 |
Callable = typing.Callable |
| 3610 |
Collection = typing.Collection |
| 3611 |
Container = typing.Container |
| 3612 |
Dict = typing.Dict |
| 3613 |
ForwardRef = typing.ForwardRef |
| 3614 |
FrozenSet = typing.FrozenSet |
| 3615 |
Generic = typing.Generic |
| 3616 |
Hashable = typing.Hashable |
| 3617 |
IO = typing.IO |
| 3618 |
ItemsView = typing.ItemsView |
| 3619 |
Iterable = typing.Iterable |
| 3620 |
Iterator = typing.Iterator |
| 3621 |
KeysView = typing.KeysView |
| 3622 |
List = typing.List |
| 3623 |
Mapping = typing.Mapping |
| 3624 |
MappingView = typing.MappingView |
| 3625 |
Match = typing.Match |
| 3626 |
MutableMapping = typing.MutableMapping |
| 3627 |
MutableSequence = typing.MutableSequence |
| 3628 |
MutableSet = typing.MutableSet |
| 3629 |
Optional = typing.Optional |
| 3630 |
Pattern = typing.Pattern |
| 3631 |
Reversible = typing.Reversible |
| 3632 |
Sequence = typing.Sequence |
| 3633 |
Set = typing.Set |
| 3634 |
Sized = typing.Sized |
| 3635 |
TextIO = typing.TextIO |
| 3636 |
Tuple = typing.Tuple |
| 3637 |
Union = typing.Union |
| 3638 |
ValuesView = typing.ValuesView |
| 3639 |
cast = typing.cast |
| 3640 |
no_type_check = typing.no_type_check |
| 3641 |
no_type_check_decorator = typing.no_type_check_decorator |