typing_extensions.py 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296
  1. import abc
  2. import collections
  3. import collections.abc
  4. import operator
  5. import sys
  6. import typing
  7. # After PEP 560, internal typing API was substantially reworked.
  8. # This is especially important for Protocol class which uses internal APIs
  9. # quite extensively.
  10. PEP_560 = sys.version_info[:3] >= (3, 7, 0)
  11. if PEP_560:
  12. GenericMeta = type
  13. else:
  14. # 3.6
  15. from typing import GenericMeta, _type_vars # noqa
  16. # The two functions below are copies of typing internal helpers.
  17. # They are needed by _ProtocolMeta
  18. def _no_slots_copy(dct):
  19. dict_copy = dict(dct)
  20. if '__slots__' in dict_copy:
  21. for slot in dict_copy['__slots__']:
  22. dict_copy.pop(slot, None)
  23. return dict_copy
  24. def _check_generic(cls, parameters):
  25. if not cls.__parameters__:
  26. raise TypeError(f"{cls} is not a generic class")
  27. alen = len(parameters)
  28. elen = len(cls.__parameters__)
  29. if alen != elen:
  30. raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments for {cls};"
  31. f" actual {alen}, expected {elen}")
  32. # Please keep __all__ alphabetized within each category.
  33. __all__ = [
  34. # Super-special typing primitives.
  35. 'ClassVar',
  36. 'Concatenate',
  37. 'Final',
  38. 'ParamSpec',
  39. 'Self',
  40. 'Type',
  41. # ABCs (from collections.abc).
  42. 'Awaitable',
  43. 'AsyncIterator',
  44. 'AsyncIterable',
  45. 'Coroutine',
  46. 'AsyncGenerator',
  47. 'AsyncContextManager',
  48. 'ChainMap',
  49. # Concrete collection types.
  50. 'ContextManager',
  51. 'Counter',
  52. 'Deque',
  53. 'DefaultDict',
  54. 'OrderedDict',
  55. 'TypedDict',
  56. # Structural checks, a.k.a. protocols.
  57. 'SupportsIndex',
  58. # One-off things.
  59. 'Annotated',
  60. 'final',
  61. 'IntVar',
  62. 'Literal',
  63. 'NewType',
  64. 'overload',
  65. 'Protocol',
  66. 'runtime',
  67. 'runtime_checkable',
  68. 'Text',
  69. 'TypeAlias',
  70. 'TypeGuard',
  71. 'TYPE_CHECKING',
  72. ]
  73. if PEP_560:
  74. __all__.extend(["get_args", "get_origin", "get_type_hints"])
  75. # 3.6.2+
  76. if hasattr(typing, 'NoReturn'):
  77. NoReturn = typing.NoReturn
  78. # 3.6.0-3.6.1
  79. else:
  80. class _NoReturn(typing._FinalTypingBase, _root=True):
  81. """Special type indicating functions that never return.
  82. Example::
  83. from typing import NoReturn
  84. def stop() -> NoReturn:
  85. raise Exception('no way')
  86. This type is invalid in other positions, e.g., ``List[NoReturn]``
  87. will fail in static type checkers.
  88. """
  89. __slots__ = ()
  90. def __instancecheck__(self, obj):
  91. raise TypeError("NoReturn cannot be used with isinstance().")
  92. def __subclasscheck__(self, cls):
  93. raise TypeError("NoReturn cannot be used with issubclass().")
  94. NoReturn = _NoReturn(_root=True)
  95. # Some unconstrained type variables. These are used by the container types.
  96. # (These are not for export.)
  97. T = typing.TypeVar('T') # Any type.
  98. KT = typing.TypeVar('KT') # Key type.
  99. VT = typing.TypeVar('VT') # Value type.
  100. T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
  101. T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
  102. ClassVar = typing.ClassVar
  103. # On older versions of typing there is an internal class named "Final".
  104. # 3.8+
  105. if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
  106. Final = typing.Final
  107. # 3.7
  108. elif sys.version_info[:2] >= (3, 7):
  109. class _FinalForm(typing._SpecialForm, _root=True):
  110. def __repr__(self):
  111. return 'typing_extensions.' + self._name
  112. def __getitem__(self, parameters):
  113. item = typing._type_check(parameters,
  114. f'{self._name} accepts only single type')
  115. return typing._GenericAlias(self, (item,))
  116. Final = _FinalForm('Final',
  117. doc="""A special typing construct to indicate that a name
  118. cannot be re-assigned or overridden in a subclass.
  119. For example:
  120. MAX_SIZE: Final = 9000
  121. MAX_SIZE += 1 # Error reported by type checker
  122. class Connection:
  123. TIMEOUT: Final[int] = 10
  124. class FastConnector(Connection):
  125. TIMEOUT = 1 # Error reported by type checker
  126. There is no runtime checking of these properties.""")
  127. # 3.6
  128. else:
  129. class _Final(typing._FinalTypingBase, _root=True):
  130. """A special typing construct to indicate that a name
  131. cannot be re-assigned or overridden in a subclass.
  132. For example:
  133. MAX_SIZE: Final = 9000
  134. MAX_SIZE += 1 # Error reported by type checker
  135. class Connection:
  136. TIMEOUT: Final[int] = 10
  137. class FastConnector(Connection):
  138. TIMEOUT = 1 # Error reported by type checker
  139. There is no runtime checking of these properties.
  140. """
  141. __slots__ = ('__type__',)
  142. def __init__(self, tp=None, **kwds):
  143. self.__type__ = tp
  144. def __getitem__(self, item):
  145. cls = type(self)
  146. if self.__type__ is None:
  147. return cls(typing._type_check(item,
  148. f'{cls.__name__[1:]} accepts only single type.'),
  149. _root=True)
  150. raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')
  151. def _eval_type(self, globalns, localns):
  152. new_tp = typing._eval_type(self.__type__, globalns, localns)
  153. if new_tp == self.__type__:
  154. return self
  155. return type(self)(new_tp, _root=True)
  156. def __repr__(self):
  157. r = super().__repr__()
  158. if self.__type__ is not None:
  159. r += f'[{typing._type_repr(self.__type__)}]'
  160. return r
  161. def __hash__(self):
  162. return hash((type(self).__name__, self.__type__))
  163. def __eq__(self, other):
  164. if not isinstance(other, _Final):
  165. return NotImplemented
  166. if self.__type__ is not None:
  167. return self.__type__ == other.__type__
  168. return self is other
  169. Final = _Final(_root=True)
  170. # 3.8+
  171. if hasattr(typing, 'final'):
  172. final = typing.final
  173. # 3.6-3.7
  174. else:
  175. def final(f):
  176. """This decorator can be used to indicate to type checkers that
  177. the decorated method cannot be overridden, and decorated class
  178. cannot be subclassed. For example:
  179. class Base:
  180. @final
  181. def done(self) -> None:
  182. ...
  183. class Sub(Base):
  184. def done(self) -> None: # Error reported by type checker
  185. ...
  186. @final
  187. class Leaf:
  188. ...
  189. class Other(Leaf): # Error reported by type checker
  190. ...
  191. There is no runtime checking of these properties.
  192. """
  193. return f
  194. def IntVar(name):
  195. return typing.TypeVar(name)
  196. # 3.8+:
  197. if hasattr(typing, 'Literal'):
  198. Literal = typing.Literal
  199. # 3.7:
  200. elif sys.version_info[:2] >= (3, 7):
  201. class _LiteralForm(typing._SpecialForm, _root=True):
  202. def __repr__(self):
  203. return 'typing_extensions.' + self._name
  204. def __getitem__(self, parameters):
  205. return typing._GenericAlias(self, parameters)
  206. Literal = _LiteralForm('Literal',
  207. doc="""A type that can be used to indicate to type checkers
  208. that the corresponding value has a value literally equivalent
  209. to the provided parameter. For example:
  210. var: Literal[4] = 4
  211. The type checker understands that 'var' is literally equal to
  212. the value 4 and no other value.
  213. Literal[...] cannot be subclassed. There is no runtime
  214. checking verifying that the parameter is actually a value
  215. instead of a type.""")
  216. # 3.6:
  217. else:
  218. class _Literal(typing._FinalTypingBase, _root=True):
  219. """A type that can be used to indicate to type checkers that the
  220. corresponding value has a value literally equivalent to the
  221. provided parameter. For example:
  222. var: Literal[4] = 4
  223. The type checker understands that 'var' is literally equal to the
  224. value 4 and no other value.
  225. Literal[...] cannot be subclassed. There is no runtime checking
  226. verifying that the parameter is actually a value instead of a type.
  227. """
  228. __slots__ = ('__values__',)
  229. def __init__(self, values=None, **kwds):
  230. self.__values__ = values
  231. def __getitem__(self, values):
  232. cls = type(self)
  233. if self.__values__ is None:
  234. if not isinstance(values, tuple):
  235. values = (values,)
  236. return cls(values, _root=True)
  237. raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')
  238. def _eval_type(self, globalns, localns):
  239. return self
  240. def __repr__(self):
  241. r = super().__repr__()
  242. if self.__values__ is not None:
  243. r += f'[{", ".join(map(typing._type_repr, self.__values__))}]'
  244. return r
  245. def __hash__(self):
  246. return hash((type(self).__name__, self.__values__))
  247. def __eq__(self, other):
  248. if not isinstance(other, _Literal):
  249. return NotImplemented
  250. if self.__values__ is not None:
  251. return self.__values__ == other.__values__
  252. return self is other
  253. Literal = _Literal(_root=True)
  254. _overload_dummy = typing._overload_dummy # noqa
  255. overload = typing.overload
  256. # This is not a real generic class. Don't use outside annotations.
  257. Type = typing.Type
  258. # Various ABCs mimicking those in collections.abc.
  259. # A few are simply re-exported for completeness.
  260. class _ExtensionsGenericMeta(GenericMeta):
  261. def __subclasscheck__(self, subclass):
  262. """This mimics a more modern GenericMeta.__subclasscheck__() logic
  263. (that does not have problems with recursion) to work around interactions
  264. between collections, typing, and typing_extensions on older
  265. versions of Python, see https://github.com/python/typing/issues/501.
  266. """
  267. if self.__origin__ is not None:
  268. if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
  269. raise TypeError("Parameterized generics cannot be used with class "
  270. "or instance checks")
  271. return False
  272. if not self.__extra__:
  273. return super().__subclasscheck__(subclass)
  274. res = self.__extra__.__subclasshook__(subclass)
  275. if res is not NotImplemented:
  276. return res
  277. if self.__extra__ in subclass.__mro__:
  278. return True
  279. for scls in self.__extra__.__subclasses__():
  280. if isinstance(scls, GenericMeta):
  281. continue
  282. if issubclass(subclass, scls):
  283. return True
  284. return False
  285. Awaitable = typing.Awaitable
  286. Coroutine = typing.Coroutine
  287. AsyncIterable = typing.AsyncIterable
  288. AsyncIterator = typing.AsyncIterator
  289. # 3.6.1+
  290. if hasattr(typing, 'Deque'):
  291. Deque = typing.Deque
  292. # 3.6.0
  293. else:
  294. class Deque(collections.deque, typing.MutableSequence[T],
  295. metaclass=_ExtensionsGenericMeta,
  296. extra=collections.deque):
  297. __slots__ = ()
  298. def __new__(cls, *args, **kwds):
  299. if cls._gorg is Deque:
  300. return collections.deque(*args, **kwds)
  301. return typing._generic_new(collections.deque, cls, *args, **kwds)
  302. ContextManager = typing.ContextManager
  303. # 3.6.2+
  304. if hasattr(typing, 'AsyncContextManager'):
  305. AsyncContextManager = typing.AsyncContextManager
  306. # 3.6.0-3.6.1
  307. else:
  308. from _collections_abc import _check_methods as _check_methods_in_mro # noqa
  309. class AsyncContextManager(typing.Generic[T_co]):
  310. __slots__ = ()
  311. async def __aenter__(self):
  312. return self
  313. @abc.abstractmethod
  314. async def __aexit__(self, exc_type, exc_value, traceback):
  315. return None
  316. @classmethod
  317. def __subclasshook__(cls, C):
  318. if cls is AsyncContextManager:
  319. return _check_methods_in_mro(C, "__aenter__", "__aexit__")
  320. return NotImplemented
  321. DefaultDict = typing.DefaultDict
  322. # 3.7.2+
  323. if hasattr(typing, 'OrderedDict'):
  324. OrderedDict = typing.OrderedDict
  325. # 3.7.0-3.7.2
  326. elif (3, 7, 0) <= sys.version_info[:3] < (3, 7, 2):
  327. OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))
  328. # 3.6
  329. else:
  330. class OrderedDict(collections.OrderedDict, typing.MutableMapping[KT, VT],
  331. metaclass=_ExtensionsGenericMeta,
  332. extra=collections.OrderedDict):
  333. __slots__ = ()
  334. def __new__(cls, *args, **kwds):
  335. if cls._gorg is OrderedDict:
  336. return collections.OrderedDict(*args, **kwds)
  337. return typing._generic_new(collections.OrderedDict, cls, *args, **kwds)
  338. # 3.6.2+
  339. if hasattr(typing, 'Counter'):
  340. Counter = typing.Counter
  341. # 3.6.0-3.6.1
  342. else:
  343. class Counter(collections.Counter,
  344. typing.Dict[T, int],
  345. metaclass=_ExtensionsGenericMeta, extra=collections.Counter):
  346. __slots__ = ()
  347. def __new__(cls, *args, **kwds):
  348. if cls._gorg is Counter:
  349. return collections.Counter(*args, **kwds)
  350. return typing._generic_new(collections.Counter, cls, *args, **kwds)
  351. # 3.6.1+
  352. if hasattr(typing, 'ChainMap'):
  353. ChainMap = typing.ChainMap
  354. elif hasattr(collections, 'ChainMap'):
  355. class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT],
  356. metaclass=_ExtensionsGenericMeta,
  357. extra=collections.ChainMap):
  358. __slots__ = ()
  359. def __new__(cls, *args, **kwds):
  360. if cls._gorg is ChainMap:
  361. return collections.ChainMap(*args, **kwds)
  362. return typing._generic_new(collections.ChainMap, cls, *args, **kwds)
  363. # 3.6.1+
  364. if hasattr(typing, 'AsyncGenerator'):
  365. AsyncGenerator = typing.AsyncGenerator
  366. # 3.6.0
  367. else:
  368. class AsyncGenerator(AsyncIterator[T_co], typing.Generic[T_co, T_contra],
  369. metaclass=_ExtensionsGenericMeta,
  370. extra=collections.abc.AsyncGenerator):
  371. __slots__ = ()
  372. NewType = typing.NewType
  373. Text = typing.Text
  374. TYPE_CHECKING = typing.TYPE_CHECKING
  375. def _gorg(cls):
  376. """This function exists for compatibility with old typing versions."""
  377. assert isinstance(cls, GenericMeta)
  378. if hasattr(cls, '_gorg'):
  379. return cls._gorg
  380. while cls.__origin__ is not None:
  381. cls = cls.__origin__
  382. return cls
  383. _PROTO_WHITELIST = ['Callable', 'Awaitable',
  384. 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
  385. 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
  386. 'ContextManager', 'AsyncContextManager']
  387. def _get_protocol_attrs(cls):
  388. attrs = set()
  389. for base in cls.__mro__[:-1]: # without object
  390. if base.__name__ in ('Protocol', 'Generic'):
  391. continue
  392. annotations = getattr(base, '__annotations__', {})
  393. for attr in list(base.__dict__.keys()) + list(annotations.keys()):
  394. if (not attr.startswith('_abc_') and attr not in (
  395. '__abstractmethods__', '__annotations__', '__weakref__',
  396. '_is_protocol', '_is_runtime_protocol', '__dict__',
  397. '__args__', '__slots__',
  398. '__next_in_mro__', '__parameters__', '__origin__',
  399. '__orig_bases__', '__extra__', '__tree_hash__',
  400. '__doc__', '__subclasshook__', '__init__', '__new__',
  401. '__module__', '_MutableMapping__marker', '_gorg')):
  402. attrs.add(attr)
  403. return attrs
  404. def _is_callable_members_only(cls):
  405. return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
  406. # 3.8+
  407. if hasattr(typing, 'Protocol'):
  408. Protocol = typing.Protocol
  409. # 3.7
  410. elif PEP_560:
  411. from typing import _collect_type_vars # noqa
  412. def _no_init(self, *args, **kwargs):
  413. if type(self)._is_protocol:
  414. raise TypeError('Protocols cannot be instantiated')
  415. class _ProtocolMeta(abc.ABCMeta):
  416. # This metaclass is a bit unfortunate and exists only because of the lack
  417. # of __instancehook__.
  418. def __instancecheck__(cls, instance):
  419. # We need this method for situations where attributes are
  420. # assigned in __init__.
  421. if ((not getattr(cls, '_is_protocol', False) or
  422. _is_callable_members_only(cls)) and
  423. issubclass(instance.__class__, cls)):
  424. return True
  425. if cls._is_protocol:
  426. if all(hasattr(instance, attr) and
  427. (not callable(getattr(cls, attr, None)) or
  428. getattr(instance, attr) is not None)
  429. for attr in _get_protocol_attrs(cls)):
  430. return True
  431. return super().__instancecheck__(instance)
  432. class Protocol(metaclass=_ProtocolMeta):
  433. # There is quite a lot of overlapping code with typing.Generic.
  434. # Unfortunately it is hard to avoid this while these live in two different
  435. # modules. The duplicated code will be removed when Protocol is moved to typing.
  436. """Base class for protocol classes. Protocol classes are defined as::
  437. class Proto(Protocol):
  438. def meth(self) -> int:
  439. ...
  440. Such classes are primarily used with static type checkers that recognize
  441. structural subtyping (static duck-typing), for example::
  442. class C:
  443. def meth(self) -> int:
  444. return 0
  445. def func(x: Proto) -> int:
  446. return x.meth()
  447. func(C()) # Passes static type check
  448. See PEP 544 for details. Protocol classes decorated with
  449. @typing_extensions.runtime act as simple-minded runtime protocol that checks
  450. only the presence of given attributes, ignoring their type signatures.
  451. Protocol classes can be generic, they are defined as::
  452. class GenProto(Protocol[T]):
  453. def meth(self) -> T:
  454. ...
  455. """
  456. __slots__ = ()
  457. _is_protocol = True
  458. def __new__(cls, *args, **kwds):
  459. if cls is Protocol:
  460. raise TypeError("Type Protocol cannot be instantiated; "
  461. "it can only be used as a base class")
  462. return super().__new__(cls)
  463. @typing._tp_cache
  464. def __class_getitem__(cls, params):
  465. if not isinstance(params, tuple):
  466. params = (params,)
  467. if not params and cls is not typing.Tuple:
  468. raise TypeError(
  469. f"Parameter list to {cls.__qualname__}[...] cannot be empty")
  470. msg = "Parameters to generic types must be types."
  471. params = tuple(typing._type_check(p, msg) for p in params) # noqa
  472. if cls is Protocol:
  473. # Generic can only be subscripted with unique type variables.
  474. if not all(isinstance(p, typing.TypeVar) for p in params):
  475. i = 0
  476. while isinstance(params[i], typing.TypeVar):
  477. i += 1
  478. raise TypeError(
  479. "Parameters to Protocol[...] must all be type variables."
  480. f" Parameter {i + 1} is {params[i]}")
  481. if len(set(params)) != len(params):
  482. raise TypeError(
  483. "Parameters to Protocol[...] must all be unique")
  484. else:
  485. # Subscripting a regular Generic subclass.
  486. _check_generic(cls, params)
  487. return typing._GenericAlias(cls, params)
  488. def __init_subclass__(cls, *args, **kwargs):
  489. tvars = []
  490. if '__orig_bases__' in cls.__dict__:
  491. error = typing.Generic in cls.__orig_bases__
  492. else:
  493. error = typing.Generic in cls.__bases__
  494. if error:
  495. raise TypeError("Cannot inherit from plain Generic")
  496. if '__orig_bases__' in cls.__dict__:
  497. tvars = _collect_type_vars(cls.__orig_bases__)
  498. # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
  499. # If found, tvars must be a subset of it.
  500. # If not found, tvars is it.
  501. # Also check for and reject plain Generic,
  502. # and reject multiple Generic[...] and/or Protocol[...].
  503. gvars = None
  504. for base in cls.__orig_bases__:
  505. if (isinstance(base, typing._GenericAlias) and
  506. base.__origin__ in (typing.Generic, Protocol)):
  507. # for error messages
  508. the_base = base.__origin__.__name__
  509. if gvars is not None:
  510. raise TypeError(
  511. "Cannot inherit from Generic[...]"
  512. " and/or Protocol[...] multiple types.")
  513. gvars = base.__parameters__
  514. if gvars is None:
  515. gvars = tvars
  516. else:
  517. tvarset = set(tvars)
  518. gvarset = set(gvars)
  519. if not tvarset <= gvarset:
  520. s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
  521. s_args = ', '.join(str(g) for g in gvars)
  522. raise TypeError(f"Some type variables ({s_vars}) are"
  523. f" not listed in {the_base}[{s_args}]")
  524. tvars = gvars
  525. cls.__parameters__ = tuple(tvars)
  526. # Determine if this is a protocol or a concrete subclass.
  527. if not cls.__dict__.get('_is_protocol', None):
  528. cls._is_protocol = any(b is Protocol for b in cls.__bases__)
  529. # Set (or override) the protocol subclass hook.
  530. def _proto_hook(other):
  531. if not cls.__dict__.get('_is_protocol', None):
  532. return NotImplemented
  533. if not getattr(cls, '_is_runtime_protocol', False):
  534. if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
  535. return NotImplemented
  536. raise TypeError("Instance and class checks can only be used with"
  537. " @runtime protocols")
  538. if not _is_callable_members_only(cls):
  539. if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
  540. return NotImplemented
  541. raise TypeError("Protocols with non-method members"
  542. " don't support issubclass()")
  543. if not isinstance(other, type):
  544. # Same error as for issubclass(1, int)
  545. raise TypeError('issubclass() arg 1 must be a class')
  546. for attr in _get_protocol_attrs(cls):
  547. for base in other.__mro__:
  548. if attr in base.__dict__:
  549. if base.__dict__[attr] is None:
  550. return NotImplemented
  551. break
  552. annotations = getattr(base, '__annotations__', {})
  553. if (isinstance(annotations, typing.Mapping) and
  554. attr in annotations and
  555. isinstance(other, _ProtocolMeta) and
  556. other._is_protocol):
  557. break
  558. else:
  559. return NotImplemented
  560. return True
  561. if '__subclasshook__' not in cls.__dict__:
  562. cls.__subclasshook__ = _proto_hook
  563. # We have nothing more to do for non-protocols.
  564. if not cls._is_protocol:
  565. return
  566. # Check consistency of bases.
  567. for base in cls.__bases__:
  568. if not (base in (object, typing.Generic) or
  569. base.__module__ == 'collections.abc' and
  570. base.__name__ in _PROTO_WHITELIST or
  571. isinstance(base, _ProtocolMeta) and base._is_protocol):
  572. raise TypeError('Protocols can only inherit from other'
  573. f' protocols, got {repr(base)}')
  574. cls.__init__ = _no_init
  575. # 3.6
  576. else:
  577. from typing import _next_in_mro, _type_check # noqa
  578. def _no_init(self, *args, **kwargs):
  579. if type(self)._is_protocol:
  580. raise TypeError('Protocols cannot be instantiated')
  581. class _ProtocolMeta(GenericMeta):
  582. """Internal metaclass for Protocol.
  583. This exists so Protocol classes can be generic without deriving
  584. from Generic.
  585. """
  586. def __new__(cls, name, bases, namespace,
  587. tvars=None, args=None, origin=None, extra=None, orig_bases=None):
  588. # This is just a version copied from GenericMeta.__new__ that
  589. # includes "Protocol" special treatment. (Comments removed for brevity.)
  590. assert extra is None # Protocols should not have extra
  591. if tvars is not None:
  592. assert origin is not None
  593. assert all(isinstance(t, typing.TypeVar) for t in tvars), tvars
  594. else:
  595. tvars = _type_vars(bases)
  596. gvars = None
  597. for base in bases:
  598. if base is typing.Generic:
  599. raise TypeError("Cannot inherit from plain Generic")
  600. if (isinstance(base, GenericMeta) and
  601. base.__origin__ in (typing.Generic, Protocol)):
  602. if gvars is not None:
  603. raise TypeError(
  604. "Cannot inherit from Generic[...] or"
  605. " Protocol[...] multiple times.")
  606. gvars = base.__parameters__
  607. if gvars is None:
  608. gvars = tvars
  609. else:
  610. tvarset = set(tvars)
  611. gvarset = set(gvars)
  612. if not tvarset <= gvarset:
  613. s_vars = ", ".join(str(t) for t in tvars if t not in gvarset)
  614. s_args = ", ".join(str(g) for g in gvars)
  615. cls_name = "Generic" if any(b.__origin__ is typing.Generic
  616. for b in bases) else "Protocol"
  617. raise TypeError(f"Some type variables ({s_vars}) are"
  618. f" not listed in {cls_name}[{s_args}]")
  619. tvars = gvars
  620. initial_bases = bases
  621. if (extra is not None and type(extra) is abc.ABCMeta and
  622. extra not in bases):
  623. bases = (extra,) + bases
  624. bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b
  625. for b in bases)
  626. if any(isinstance(b, GenericMeta) and b is not typing.Generic for b in bases):
  627. bases = tuple(b for b in bases if b is not typing.Generic)
  628. namespace.update({'__origin__': origin, '__extra__': extra})
  629. self = super(GenericMeta, cls).__new__(cls, name, bases, namespace,
  630. _root=True)
  631. super(GenericMeta, self).__setattr__('_gorg',
  632. self if not origin else
  633. _gorg(origin))
  634. self.__parameters__ = tvars
  635. self.__args__ = tuple(... if a is typing._TypingEllipsis else
  636. () if a is typing._TypingEmpty else
  637. a for a in args) if args else None
  638. self.__next_in_mro__ = _next_in_mro(self)
  639. if orig_bases is None:
  640. self.__orig_bases__ = initial_bases
  641. elif origin is not None:
  642. self._abc_registry = origin._abc_registry
  643. self._abc_cache = origin._abc_cache
  644. if hasattr(self, '_subs_tree'):
  645. self.__tree_hash__ = (hash(self._subs_tree()) if origin else
  646. super(GenericMeta, self).__hash__())
  647. return self
  648. def __init__(cls, *args, **kwargs):
  649. super().__init__(*args, **kwargs)
  650. if not cls.__dict__.get('_is_protocol', None):
  651. cls._is_protocol = any(b is Protocol or
  652. isinstance(b, _ProtocolMeta) and
  653. b.__origin__ is Protocol
  654. for b in cls.__bases__)
  655. if cls._is_protocol:
  656. for base in cls.__mro__[1:]:
  657. if not (base in (object, typing.Generic) or
  658. base.__module__ == 'collections.abc' and
  659. base.__name__ in _PROTO_WHITELIST or
  660. isinstance(base, typing.TypingMeta) and base._is_protocol or
  661. isinstance(base, GenericMeta) and
  662. base.__origin__ is typing.Generic):
  663. raise TypeError(f'Protocols can only inherit from other'
  664. f' protocols, got {repr(base)}')
  665. cls.__init__ = _no_init
  666. def _proto_hook(other):
  667. if not cls.__dict__.get('_is_protocol', None):
  668. return NotImplemented
  669. if not isinstance(other, type):
  670. # Same error as for issubclass(1, int)
  671. raise TypeError('issubclass() arg 1 must be a class')
  672. for attr in _get_protocol_attrs(cls):
  673. for base in other.__mro__:
  674. if attr in base.__dict__:
  675. if base.__dict__[attr] is None:
  676. return NotImplemented
  677. break
  678. annotations = getattr(base, '__annotations__', {})
  679. if (isinstance(annotations, typing.Mapping) and
  680. attr in annotations and
  681. isinstance(other, _ProtocolMeta) and
  682. other._is_protocol):
  683. break
  684. else:
  685. return NotImplemented
  686. return True
  687. if '__subclasshook__' not in cls.__dict__:
  688. cls.__subclasshook__ = _proto_hook
  689. def __instancecheck__(self, instance):
  690. # We need this method for situations where attributes are
  691. # assigned in __init__.
  692. if ((not getattr(self, '_is_protocol', False) or
  693. _is_callable_members_only(self)) and
  694. issubclass(instance.__class__, self)):
  695. return True
  696. if self._is_protocol:
  697. if all(hasattr(instance, attr) and
  698. (not callable(getattr(self, attr, None)) or
  699. getattr(instance, attr) is not None)
  700. for attr in _get_protocol_attrs(self)):
  701. return True
  702. return super(GenericMeta, self).__instancecheck__(instance)
  703. def __subclasscheck__(self, cls):
  704. if self.__origin__ is not None:
  705. if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
  706. raise TypeError("Parameterized generics cannot be used with class "
  707. "or instance checks")
  708. return False
  709. if (self.__dict__.get('_is_protocol', None) and
  710. not self.__dict__.get('_is_runtime_protocol', None)):
  711. if sys._getframe(1).f_globals['__name__'] in ['abc',
  712. 'functools',
  713. 'typing']:
  714. return False
  715. raise TypeError("Instance and class checks can only be used with"
  716. " @runtime protocols")
  717. if (self.__dict__.get('_is_runtime_protocol', None) and
  718. not _is_callable_members_only(self)):
  719. if sys._getframe(1).f_globals['__name__'] in ['abc',
  720. 'functools',
  721. 'typing']:
  722. return super(GenericMeta, self).__subclasscheck__(cls)
  723. raise TypeError("Protocols with non-method members"
  724. " don't support issubclass()")
  725. return super(GenericMeta, self).__subclasscheck__(cls)
  726. @typing._tp_cache
  727. def __getitem__(self, params):
  728. # We also need to copy this from GenericMeta.__getitem__ to get
  729. # special treatment of "Protocol". (Comments removed for brevity.)
  730. if not isinstance(params, tuple):
  731. params = (params,)
  732. if not params and _gorg(self) is not typing.Tuple:
  733. raise TypeError(
  734. f"Parameter list to {self.__qualname__}[...] cannot be empty")
  735. msg = "Parameters to generic types must be types."
  736. params = tuple(_type_check(p, msg) for p in params)
  737. if self in (typing.Generic, Protocol):
  738. if not all(isinstance(p, typing.TypeVar) for p in params):
  739. raise TypeError(
  740. f"Parameters to {repr(self)}[...] must all be type variables")
  741. if len(set(params)) != len(params):
  742. raise TypeError(
  743. f"Parameters to {repr(self)}[...] must all be unique")
  744. tvars = params
  745. args = params
  746. elif self in (typing.Tuple, typing.Callable):
  747. tvars = _type_vars(params)
  748. args = params
  749. elif self.__origin__ in (typing.Generic, Protocol):
  750. raise TypeError(f"Cannot subscript already-subscripted {repr(self)}")
  751. else:
  752. _check_generic(self, params)
  753. tvars = _type_vars(params)
  754. args = params
  755. prepend = (self,) if self.__origin__ is None else ()
  756. return self.__class__(self.__name__,
  757. prepend + self.__bases__,
  758. _no_slots_copy(self.__dict__),
  759. tvars=tvars,
  760. args=args,
  761. origin=self,
  762. extra=self.__extra__,
  763. orig_bases=self.__orig_bases__)
  764. class Protocol(metaclass=_ProtocolMeta):
  765. """Base class for protocol classes. Protocol classes are defined as::
  766. class Proto(Protocol):
  767. def meth(self) -> int:
  768. ...
  769. Such classes are primarily used with static type checkers that recognize
  770. structural subtyping (static duck-typing), for example::
  771. class C:
  772. def meth(self) -> int:
  773. return 0
  774. def func(x: Proto) -> int:
  775. return x.meth()
  776. func(C()) # Passes static type check
  777. See PEP 544 for details. Protocol classes decorated with
  778. @typing_extensions.runtime act as simple-minded runtime protocol that checks
  779. only the presence of given attributes, ignoring their type signatures.
  780. Protocol classes can be generic, they are defined as::
  781. class GenProto(Protocol[T]):
  782. def meth(self) -> T:
  783. ...
  784. """
  785. __slots__ = ()
  786. _is_protocol = True
  787. def __new__(cls, *args, **kwds):
  788. if _gorg(cls) is Protocol:
  789. raise TypeError("Type Protocol cannot be instantiated; "
  790. "it can be used only as a base class")
  791. return typing._generic_new(cls.__next_in_mro__, cls, *args, **kwds)
  792. # 3.8+
  793. if hasattr(typing, 'runtime_checkable'):
  794. runtime_checkable = typing.runtime_checkable
  795. # 3.6-3.7
  796. else:
  797. def runtime_checkable(cls):
  798. """Mark a protocol class as a runtime protocol, so that it
  799. can be used with isinstance() and issubclass(). Raise TypeError
  800. if applied to a non-protocol class.
  801. This allows a simple-minded structural check very similar to the
  802. one-offs in collections.abc such as Hashable.
  803. """
  804. if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
  805. raise TypeError('@runtime_checkable can be only applied to protocol classes,'
  806. f' got {cls!r}')
  807. cls._is_runtime_protocol = True
  808. return cls
  809. # Exists for backwards compatibility.
  810. runtime = runtime_checkable
  811. # 3.8+
  812. if hasattr(typing, 'SupportsIndex'):
  813. SupportsIndex = typing.SupportsIndex
  814. # 3.6-3.7
  815. else:
  816. @runtime_checkable
  817. class SupportsIndex(Protocol):
  818. __slots__ = ()
  819. @abc.abstractmethod
  820. def __index__(self) -> int:
  821. pass
  822. if sys.version_info >= (3, 9, 2):
  823. # The standard library TypedDict in Python 3.8 does not store runtime information
  824. # about which (if any) keys are optional. See https://bugs.python.org/issue38834
  825. # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
  826. # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
  827. TypedDict = typing.TypedDict
  828. else:
  829. def _check_fails(cls, other):
  830. try:
  831. if sys._getframe(1).f_globals['__name__'] not in ['abc',
  832. 'functools',
  833. 'typing']:
  834. # Typed dicts are only for static structural subtyping.
  835. raise TypeError('TypedDict does not support instance and class checks')
  836. except (AttributeError, ValueError):
  837. pass
  838. return False
  839. def _dict_new(*args, **kwargs):
  840. if not args:
  841. raise TypeError('TypedDict.__new__(): not enough arguments')
  842. _, args = args[0], args[1:] # allow the "cls" keyword be passed
  843. return dict(*args, **kwargs)
  844. _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'
  845. def _typeddict_new(*args, total=True, **kwargs):
  846. if not args:
  847. raise TypeError('TypedDict.__new__(): not enough arguments')
  848. _, args = args[0], args[1:] # allow the "cls" keyword be passed
  849. if args:
  850. typename, args = args[0], args[1:] # allow the "_typename" keyword be passed
  851. elif '_typename' in kwargs:
  852. typename = kwargs.pop('_typename')
  853. import warnings
  854. warnings.warn("Passing '_typename' as keyword argument is deprecated",
  855. DeprecationWarning, stacklevel=2)
  856. else:
  857. raise TypeError("TypedDict.__new__() missing 1 required positional "
  858. "argument: '_typename'")
  859. if args:
  860. try:
  861. fields, = args # allow the "_fields" keyword be passed
  862. except ValueError:
  863. raise TypeError('TypedDict.__new__() takes from 2 to 3 '
  864. f'positional arguments but {len(args) + 2} '
  865. 'were given')
  866. elif '_fields' in kwargs and len(kwargs) == 1:
  867. fields = kwargs.pop('_fields')
  868. import warnings
  869. warnings.warn("Passing '_fields' as keyword argument is deprecated",
  870. DeprecationWarning, stacklevel=2)
  871. else:
  872. fields = None
  873. if fields is None:
  874. fields = kwargs
  875. elif kwargs:
  876. raise TypeError("TypedDict takes either a dict or keyword arguments,"
  877. " but not both")
  878. ns = {'__annotations__': dict(fields)}
  879. try:
  880. # Setting correct module is necessary to make typed dict classes pickleable.
  881. ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
  882. except (AttributeError, ValueError):
  883. pass
  884. return _TypedDictMeta(typename, (), ns, total=total)
  885. _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'
  886. ' /, *, total=True, **kwargs)')
  887. class _TypedDictMeta(type):
  888. def __init__(cls, name, bases, ns, total=True):
  889. super().__init__(name, bases, ns)
  890. def __new__(cls, name, bases, ns, total=True):
  891. # Create new typed dict class object.
  892. # This method is called directly when TypedDict is subclassed,
  893. # or via _typeddict_new when TypedDict is instantiated. This way
  894. # TypedDict supports all three syntaxes described in its docstring.
  895. # Subclasses and instances of TypedDict return actual dictionaries
  896. # via _dict_new.
  897. ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
  898. tp_dict = super().__new__(cls, name, (dict,), ns)
  899. annotations = {}
  900. own_annotations = ns.get('__annotations__', {})
  901. own_annotation_keys = set(own_annotations.keys())
  902. msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
  903. own_annotations = {
  904. n: typing._type_check(tp, msg) for n, tp in own_annotations.items()
  905. }
  906. required_keys = set()
  907. optional_keys = set()
  908. for base in bases:
  909. annotations.update(base.__dict__.get('__annotations__', {}))
  910. required_keys.update(base.__dict__.get('__required_keys__', ()))
  911. optional_keys.update(base.__dict__.get('__optional_keys__', ()))
  912. annotations.update(own_annotations)
  913. if total:
  914. required_keys.update(own_annotation_keys)
  915. else:
  916. optional_keys.update(own_annotation_keys)
  917. tp_dict.__annotations__ = annotations
  918. tp_dict.__required_keys__ = frozenset(required_keys)
  919. tp_dict.__optional_keys__ = frozenset(optional_keys)
  920. if not hasattr(tp_dict, '__total__'):
  921. tp_dict.__total__ = total
  922. return tp_dict
  923. __instancecheck__ = __subclasscheck__ = _check_fails
  924. TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
  925. TypedDict.__module__ = __name__
  926. TypedDict.__doc__ = \
  927. """A simple typed name space. At runtime it is equivalent to a plain dict.
  928. TypedDict creates a dictionary type that expects all of its
  929. instances to have a certain set of keys, with each key
  930. associated with a value of a consistent type. This expectation
  931. is not checked at runtime but is only enforced by type checkers.
  932. Usage::
  933. class Point2D(TypedDict):
  934. x: int
  935. y: int
  936. label: str
  937. a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
  938. b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
  939. assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
  940. The type info can be accessed via the Point2D.__annotations__ dict, and
  941. the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
  942. TypedDict supports two additional equivalent forms::
  943. Point2D = TypedDict('Point2D', x=int, y=int, label=str)
  944. Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
  945. The class syntax is only supported in Python 3.6+, while two other
  946. syntax forms work for Python 2.7 and 3.2+
  947. """
  948. # Python 3.9+ has PEP 593 (Annotated and modified get_type_hints)
  949. if hasattr(typing, 'Annotated'):
  950. Annotated = typing.Annotated
  951. get_type_hints = typing.get_type_hints
  952. # Not exported and not a public API, but needed for get_origin() and get_args()
  953. # to work.
  954. _AnnotatedAlias = typing._AnnotatedAlias
  955. # 3.7-3.8
  956. elif PEP_560:
  957. class _AnnotatedAlias(typing._GenericAlias, _root=True):
  958. """Runtime representation of an annotated type.
  959. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
  960. with extra annotations. The alias behaves like a normal typing alias,
  961. instantiating is the same as instantiating the underlying type, binding
  962. it to types is also the same.
  963. """
  964. def __init__(self, origin, metadata):
  965. if isinstance(origin, _AnnotatedAlias):
  966. metadata = origin.__metadata__ + metadata
  967. origin = origin.__origin__
  968. super().__init__(origin, origin)
  969. self.__metadata__ = metadata
  970. def copy_with(self, params):
  971. assert len(params) == 1
  972. new_type = params[0]
  973. return _AnnotatedAlias(new_type, self.__metadata__)
  974. def __repr__(self):
  975. return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
  976. f"{', '.join(repr(a) for a in self.__metadata__)}]")
  977. def __reduce__(self):
  978. return operator.getitem, (
  979. Annotated, (self.__origin__,) + self.__metadata__
  980. )
  981. def __eq__(self, other):
  982. if not isinstance(other, _AnnotatedAlias):
  983. return NotImplemented
  984. if self.__origin__ != other.__origin__:
  985. return False
  986. return self.__metadata__ == other.__metadata__
  987. def __hash__(self):
  988. return hash((self.__origin__, self.__metadata__))
  989. class Annotated:
  990. """Add context specific metadata to a type.
  991. Example: Annotated[int, runtime_check.Unsigned] indicates to the
  992. hypothetical runtime_check module that this type is an unsigned int.
  993. Every other consumer of this type can ignore this metadata and treat
  994. this type as int.
  995. The first argument to Annotated must be a valid type (and will be in
  996. the __origin__ field), the remaining arguments are kept as a tuple in
  997. the __extra__ field.
  998. Details:
  999. - It's an error to call `Annotated` with less than two arguments.
  1000. - Nested Annotated are flattened::
  1001. Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
  1002. - Instantiating an annotated type is equivalent to instantiating the
  1003. underlying type::
  1004. Annotated[C, Ann1](5) == C(5)
  1005. - Annotated can be used as a generic type alias::
  1006. Optimized = Annotated[T, runtime.Optimize()]
  1007. Optimized[int] == Annotated[int, runtime.Optimize()]
  1008. OptimizedList = Annotated[List[T], runtime.Optimize()]
  1009. OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
  1010. """
  1011. __slots__ = ()
  1012. def __new__(cls, *args, **kwargs):
  1013. raise TypeError("Type Annotated cannot be instantiated.")
  1014. @typing._tp_cache
  1015. def __class_getitem__(cls, params):
  1016. if not isinstance(params, tuple) or len(params) < 2:
  1017. raise TypeError("Annotated[...] should be used "
  1018. "with at least two arguments (a type and an "
  1019. "annotation).")
  1020. msg = "Annotated[t, ...]: t must be a type."
  1021. origin = typing._type_check(params[0], msg)
  1022. metadata = tuple(params[1:])
  1023. return _AnnotatedAlias(origin, metadata)
  1024. def __init_subclass__(cls, *args, **kwargs):
  1025. raise TypeError(
  1026. f"Cannot subclass {cls.__module__}.Annotated"
  1027. )
  1028. def _strip_annotations(t):
  1029. """Strips the annotations from a given type.
  1030. """
  1031. if isinstance(t, _AnnotatedAlias):
  1032. return _strip_annotations(t.__origin__)
  1033. if isinstance(t, typing._GenericAlias):
  1034. stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
  1035. if stripped_args == t.__args__:
  1036. return t
  1037. res = t.copy_with(stripped_args)
  1038. res._special = t._special
  1039. return res
  1040. return t
  1041. def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
  1042. """Return type hints for an object.
  1043. This is often the same as obj.__annotations__, but it handles
  1044. forward references encoded as string literals, adds Optional[t] if a
  1045. default value equal to None is set and recursively replaces all
  1046. 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
  1047. The argument may be a module, class, method, or function. The annotations
  1048. are returned as a dictionary. For classes, annotations include also
  1049. inherited members.
  1050. TypeError is raised if the argument is not of a type that can contain
  1051. annotations, and an empty dictionary is returned if no annotations are
  1052. present.
  1053. BEWARE -- the behavior of globalns and localns is counterintuitive
  1054. (unless you are familiar with how eval() and exec() work). The
  1055. search order is locals first, then globals.
  1056. - If no dict arguments are passed, an attempt is made to use the
  1057. globals from obj (or the respective module's globals for classes),
  1058. and these are also used as the locals. If the object does not appear
  1059. to have globals, an empty dictionary is used.
  1060. - If one dict argument is passed, it is used for both globals and
  1061. locals.
  1062. - If two dict arguments are passed, they specify globals and
  1063. locals, respectively.
  1064. """
  1065. hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
  1066. if include_extras:
  1067. return hint
  1068. return {k: _strip_annotations(t) for k, t in hint.items()}
  1069. # 3.6
  1070. else:
  1071. def _is_dunder(name):
  1072. """Returns True if name is a __dunder_variable_name__."""
  1073. return len(name) > 4 and name.startswith('__') and name.endswith('__')
  1074. # Prior to Python 3.7 types did not have `copy_with`. A lot of the equality
  1075. # checks, argument expansion etc. are done on the _subs_tre. As a result we
  1076. # can't provide a get_type_hints function that strips out annotations.
  1077. class AnnotatedMeta(typing.GenericMeta):
  1078. """Metaclass for Annotated"""
  1079. def __new__(cls, name, bases, namespace, **kwargs):
  1080. if any(b is not object for b in bases):
  1081. raise TypeError("Cannot subclass " + str(Annotated))
  1082. return super().__new__(cls, name, bases, namespace, **kwargs)
  1083. @property
  1084. def __metadata__(self):
  1085. return self._subs_tree()[2]
  1086. def _tree_repr(self, tree):
  1087. cls, origin, metadata = tree
  1088. if not isinstance(origin, tuple):
  1089. tp_repr = typing._type_repr(origin)
  1090. else:
  1091. tp_repr = origin[0]._tree_repr(origin)
  1092. metadata_reprs = ", ".join(repr(arg) for arg in metadata)
  1093. return f'{cls}[{tp_repr}, {metadata_reprs}]'
  1094. def _subs_tree(self, tvars=None, args=None): # noqa
  1095. if self is Annotated:
  1096. return Annotated
  1097. res = super()._subs_tree(tvars=tvars, args=args)
  1098. # Flatten nested Annotated
  1099. if isinstance(res[1], tuple) and res[1][0] is Annotated:
  1100. sub_tp = res[1][1]
  1101. sub_annot = res[1][2]
  1102. return (Annotated, sub_tp, sub_annot + res[2])
  1103. return res
  1104. def _get_cons(self):
  1105. """Return the class used to create instance of this type."""
  1106. if self.__origin__ is None:
  1107. raise TypeError("Cannot get the underlying type of a "
  1108. "non-specialized Annotated type.")
  1109. tree = self._subs_tree()
  1110. while isinstance(tree, tuple) and tree[0] is Annotated:
  1111. tree = tree[1]
  1112. if isinstance(tree, tuple):
  1113. return tree[0]
  1114. else:
  1115. return tree
  1116. @typing._tp_cache
  1117. def __getitem__(self, params):
  1118. if not isinstance(params, tuple):
  1119. params = (params,)
  1120. if self.__origin__ is not None: # specializing an instantiated type
  1121. return super().__getitem__(params)
  1122. elif not isinstance(params, tuple) or len(params) < 2:
  1123. raise TypeError("Annotated[...] should be instantiated "
  1124. "with at least two arguments (a type and an "
  1125. "annotation).")
  1126. else:
  1127. msg = "Annotated[t, ...]: t must be a type."
  1128. tp = typing._type_check(params[0], msg)
  1129. metadata = tuple(params[1:])
  1130. return self.__class__(
  1131. self.__name__,
  1132. self.__bases__,
  1133. _no_slots_copy(self.__dict__),
  1134. tvars=_type_vars((tp,)),
  1135. # Metadata is a tuple so it won't be touched by _replace_args et al.
  1136. args=(tp, metadata),
  1137. origin=self,
  1138. )
  1139. def __call__(self, *args, **kwargs):
  1140. cons = self._get_cons()
  1141. result = cons(*args, **kwargs)
  1142. try:
  1143. result.__orig_class__ = self
  1144. except AttributeError:
  1145. pass
  1146. return result
  1147. def __getattr__(self, attr):
  1148. # For simplicity we just don't relay all dunder names
  1149. if self.__origin__ is not None and not _is_dunder(attr):
  1150. return getattr(self._get_cons(), attr)
  1151. raise AttributeError(attr)
  1152. def __setattr__(self, attr, value):
  1153. if _is_dunder(attr) or attr.startswith('_abc_'):
  1154. super().__setattr__(attr, value)
  1155. elif self.__origin__ is None:
  1156. raise AttributeError(attr)
  1157. else:
  1158. setattr(self._get_cons(), attr, value)
  1159. def __instancecheck__(self, obj):
  1160. raise TypeError("Annotated cannot be used with isinstance().")
  1161. def __subclasscheck__(self, cls):
  1162. raise TypeError("Annotated cannot be used with issubclass().")
  1163. class Annotated(metaclass=AnnotatedMeta):
  1164. """Add context specific metadata to a type.
  1165. Example: Annotated[int, runtime_check.Unsigned] indicates to the
  1166. hypothetical runtime_check module that this type is an unsigned int.
  1167. Every other consumer of this type can ignore this metadata and treat
  1168. this type as int.
  1169. The first argument to Annotated must be a valid type, the remaining
  1170. arguments are kept as a tuple in the __metadata__ field.
  1171. Details:
  1172. - It's an error to call `Annotated` with less than two arguments.
  1173. - Nested Annotated are flattened::
  1174. Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
  1175. - Instantiating an annotated type is equivalent to instantiating the
  1176. underlying type::
  1177. Annotated[C, Ann1](5) == C(5)
  1178. - Annotated can be used as a generic type alias::
  1179. Optimized = Annotated[T, runtime.Optimize()]
  1180. Optimized[int] == Annotated[int, runtime.Optimize()]
  1181. OptimizedList = Annotated[List[T], runtime.Optimize()]
  1182. OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
  1183. """
  1184. # Python 3.8 has get_origin() and get_args() but those implementations aren't
  1185. # Annotated-aware, so we can't use those. Python 3.9's versions don't support
  1186. # ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
  1187. if sys.version_info[:2] >= (3, 10):
  1188. get_origin = typing.get_origin
  1189. get_args = typing.get_args
  1190. # 3.7-3.9
  1191. elif PEP_560:
  1192. try:
  1193. # 3.9+
  1194. from typing import _BaseGenericAlias
  1195. except ImportError:
  1196. _BaseGenericAlias = typing._GenericAlias
  1197. try:
  1198. # 3.9+
  1199. from typing import GenericAlias
  1200. except ImportError:
  1201. GenericAlias = typing._GenericAlias
  1202. def get_origin(tp):
  1203. """Get the unsubscripted version of a type.
  1204. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
  1205. and Annotated. Return None for unsupported types. Examples::
  1206. get_origin(Literal[42]) is Literal
  1207. get_origin(int) is None
  1208. get_origin(ClassVar[int]) is ClassVar
  1209. get_origin(Generic) is Generic
  1210. get_origin(Generic[T]) is Generic
  1211. get_origin(Union[T, int]) is Union
  1212. get_origin(List[Tuple[T, T]][int]) == list
  1213. get_origin(P.args) is P
  1214. """
  1215. if isinstance(tp, _AnnotatedAlias):
  1216. return Annotated
  1217. if isinstance(tp, (typing._GenericAlias, GenericAlias, _BaseGenericAlias,
  1218. ParamSpecArgs, ParamSpecKwargs)):
  1219. return tp.__origin__
  1220. if tp is typing.Generic:
  1221. return typing.Generic
  1222. return None
  1223. def get_args(tp):
  1224. """Get type arguments with all substitutions performed.
  1225. For unions, basic simplifications used by Union constructor are performed.
  1226. Examples::
  1227. get_args(Dict[str, int]) == (str, int)
  1228. get_args(int) == ()
  1229. get_args(Union[int, Union[T, int], str][int]) == (int, str)
  1230. get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
  1231. get_args(Callable[[], T][int]) == ([], int)
  1232. """
  1233. if isinstance(tp, _AnnotatedAlias):
  1234. return (tp.__origin__,) + tp.__metadata__
  1235. if isinstance(tp, (typing._GenericAlias, GenericAlias)):
  1236. if getattr(tp, "_special", False):
  1237. return ()
  1238. res = tp.__args__
  1239. if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
  1240. res = (list(res[:-1]), res[-1])
  1241. return res
  1242. return ()
  1243. # 3.10+
  1244. if hasattr(typing, 'TypeAlias'):
  1245. TypeAlias = typing.TypeAlias
  1246. # 3.9
  1247. elif sys.version_info[:2] >= (3, 9):
  1248. class _TypeAliasForm(typing._SpecialForm, _root=True):
  1249. def __repr__(self):
  1250. return 'typing_extensions.' + self._name
  1251. @_TypeAliasForm
  1252. def TypeAlias(self, parameters):
  1253. """Special marker indicating that an assignment should
  1254. be recognized as a proper type alias definition by type
  1255. checkers.
  1256. For example::
  1257. Predicate: TypeAlias = Callable[..., bool]
  1258. It's invalid when used anywhere except as in the example above.
  1259. """
  1260. raise TypeError(f"{self} is not subscriptable")
  1261. # 3.7-3.8
  1262. elif sys.version_info[:2] >= (3, 7):
  1263. class _TypeAliasForm(typing._SpecialForm, _root=True):
  1264. def __repr__(self):
  1265. return 'typing_extensions.' + self._name
  1266. TypeAlias = _TypeAliasForm('TypeAlias',
  1267. doc="""Special marker indicating that an assignment should
  1268. be recognized as a proper type alias definition by type
  1269. checkers.
  1270. For example::
  1271. Predicate: TypeAlias = Callable[..., bool]
  1272. It's invalid when used anywhere except as in the example
  1273. above.""")
  1274. # 3.6
  1275. else:
  1276. class _TypeAliasMeta(typing.TypingMeta):
  1277. """Metaclass for TypeAlias"""
  1278. def __repr__(self):
  1279. return 'typing_extensions.TypeAlias'
  1280. class _TypeAliasBase(typing._FinalTypingBase, metaclass=_TypeAliasMeta, _root=True):
  1281. """Special marker indicating that an assignment should
  1282. be recognized as a proper type alias definition by type
  1283. checkers.
  1284. For example::
  1285. Predicate: TypeAlias = Callable[..., bool]
  1286. It's invalid when used anywhere except as in the example above.
  1287. """
  1288. __slots__ = ()
  1289. def __instancecheck__(self, obj):
  1290. raise TypeError("TypeAlias cannot be used with isinstance().")
  1291. def __subclasscheck__(self, cls):
  1292. raise TypeError("TypeAlias cannot be used with issubclass().")
  1293. def __repr__(self):
  1294. return 'typing_extensions.TypeAlias'
  1295. TypeAlias = _TypeAliasBase(_root=True)
  1296. # Python 3.10+ has PEP 612
  1297. if hasattr(typing, 'ParamSpecArgs'):
  1298. ParamSpecArgs = typing.ParamSpecArgs
  1299. ParamSpecKwargs = typing.ParamSpecKwargs
  1300. # 3.6-3.9
  1301. else:
  1302. class _Immutable:
  1303. """Mixin to indicate that object should not be copied."""
  1304. __slots__ = ()
  1305. def __copy__(self):
  1306. return self
  1307. def __deepcopy__(self, memo):
  1308. return self
  1309. class ParamSpecArgs(_Immutable):
  1310. """The args for a ParamSpec object.
  1311. Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
  1312. ParamSpecArgs objects have a reference back to their ParamSpec:
  1313. P.args.__origin__ is P
  1314. This type is meant for runtime introspection and has no special meaning to
  1315. static type checkers.
  1316. """
  1317. def __init__(self, origin):
  1318. self.__origin__ = origin
  1319. def __repr__(self):
  1320. return f"{self.__origin__.__name__}.args"
  1321. class ParamSpecKwargs(_Immutable):
  1322. """The kwargs for a ParamSpec object.
  1323. Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
  1324. ParamSpecKwargs objects have a reference back to their ParamSpec:
  1325. P.kwargs.__origin__ is P
  1326. This type is meant for runtime introspection and has no special meaning to
  1327. static type checkers.
  1328. """
  1329. def __init__(self, origin):
  1330. self.__origin__ = origin
  1331. def __repr__(self):
  1332. return f"{self.__origin__.__name__}.kwargs"
  1333. # 3.10+
  1334. if hasattr(typing, 'ParamSpec'):
  1335. ParamSpec = typing.ParamSpec
  1336. # 3.6-3.9
  1337. else:
  1338. # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
  1339. class ParamSpec(list):
  1340. """Parameter specification variable.
  1341. Usage::
  1342. P = ParamSpec('P')
  1343. Parameter specification variables exist primarily for the benefit of static
  1344. type checkers. They are used to forward the parameter types of one
  1345. callable to another callable, a pattern commonly found in higher order
  1346. functions and decorators. They are only valid when used in ``Concatenate``,
  1347. or s the first argument to ``Callable``. In Python 3.10 and higher,
  1348. they are also supported in user-defined Generics at runtime.
  1349. See class Generic for more information on generic types. An
  1350. example for annotating a decorator::
  1351. T = TypeVar('T')
  1352. P = ParamSpec('P')
  1353. def add_logging(f: Callable[P, T]) -> Callable[P, T]:
  1354. '''A type-safe decorator to add logging to a function.'''
  1355. def inner(*args: P.args, **kwargs: P.kwargs) -> T:
  1356. logging.info(f'{f.__name__} was called')
  1357. return f(*args, **kwargs)
  1358. return inner
  1359. @add_logging
  1360. def add_two(x: float, y: float) -> float:
  1361. '''Add two numbers together.'''
  1362. return x + y
  1363. Parameter specification variables defined with covariant=True or
  1364. contravariant=True can be used to declare covariant or contravariant
  1365. generic types. These keyword arguments are valid, but their actual semantics
  1366. are yet to be decided. See PEP 612 for details.
  1367. Parameter specification variables can be introspected. e.g.:
  1368. P.__name__ == 'T'
  1369. P.__bound__ == None
  1370. P.__covariant__ == False
  1371. P.__contravariant__ == False
  1372. Note that only parameter specification variables defined in global scope can
  1373. be pickled.
  1374. """
  1375. # Trick Generic __parameters__.
  1376. __class__ = typing.TypeVar
  1377. @property
  1378. def args(self):
  1379. return ParamSpecArgs(self)
  1380. @property
  1381. def kwargs(self):
  1382. return ParamSpecKwargs(self)
  1383. def __init__(self, name, *, bound=None, covariant=False, contravariant=False):
  1384. super().__init__([self])
  1385. self.__name__ = name
  1386. self.__covariant__ = bool(covariant)
  1387. self.__contravariant__ = bool(contravariant)
  1388. if bound:
  1389. self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
  1390. else:
  1391. self.__bound__ = None
  1392. # for pickling:
  1393. try:
  1394. def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
  1395. except (AttributeError, ValueError):
  1396. def_mod = None
  1397. if def_mod != 'typing_extensions':
  1398. self.__module__ = def_mod
  1399. def __repr__(self):
  1400. if self.__covariant__:
  1401. prefix = '+'
  1402. elif self.__contravariant__:
  1403. prefix = '-'
  1404. else:
  1405. prefix = '~'
  1406. return prefix + self.__name__
  1407. def __hash__(self):
  1408. return object.__hash__(self)
  1409. def __eq__(self, other):
  1410. return self is other
  1411. def __reduce__(self):
  1412. return self.__name__
  1413. # Hack to get typing._type_check to pass.
  1414. def __call__(self, *args, **kwargs):
  1415. pass
  1416. if not PEP_560:
  1417. # Only needed in 3.6.
  1418. def _get_type_vars(self, tvars):
  1419. if self not in tvars:
  1420. tvars.append(self)
  1421. # 3.6-3.9
  1422. if not hasattr(typing, 'Concatenate'):
  1423. # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
  1424. class _ConcatenateGenericAlias(list):
  1425. # Trick Generic into looking into this for __parameters__.
  1426. if PEP_560:
  1427. __class__ = typing._GenericAlias
  1428. else:
  1429. __class__ = typing._TypingBase
  1430. # Flag in 3.8.
  1431. _special = False
  1432. # Attribute in 3.6 and earlier.
  1433. _gorg = typing.Generic
  1434. def __init__(self, origin, args):
  1435. super().__init__(args)
  1436. self.__origin__ = origin
  1437. self.__args__ = args
  1438. def __repr__(self):
  1439. _type_repr = typing._type_repr
  1440. return (f'{_type_repr(self.__origin__)}'
  1441. f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
  1442. def __hash__(self):
  1443. return hash((self.__origin__, self.__args__))
  1444. # Hack to get typing._type_check to pass in Generic.
  1445. def __call__(self, *args, **kwargs):
  1446. pass
  1447. @property
  1448. def __parameters__(self):
  1449. return tuple(
  1450. tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
  1451. )
  1452. if not PEP_560:
  1453. # Only required in 3.6.
  1454. def _get_type_vars(self, tvars):
  1455. if self.__origin__ and self.__parameters__:
  1456. typing._get_type_vars(self.__parameters__, tvars)
  1457. # 3.6-3.9
  1458. @typing._tp_cache
  1459. def _concatenate_getitem(self, parameters):
  1460. if parameters == ():
  1461. raise TypeError("Cannot take a Concatenate of no types.")
  1462. if not isinstance(parameters, tuple):
  1463. parameters = (parameters,)
  1464. if not isinstance(parameters[-1], ParamSpec):
  1465. raise TypeError("The last parameter to Concatenate should be a "
  1466. "ParamSpec variable.")
  1467. msg = "Concatenate[arg, ...]: each arg must be a type."
  1468. parameters = tuple(typing._type_check(p, msg) for p in parameters)
  1469. return _ConcatenateGenericAlias(self, parameters)
  1470. # 3.10+
  1471. if hasattr(typing, 'Concatenate'):
  1472. Concatenate = typing.Concatenate
  1473. _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa
  1474. # 3.9
  1475. elif sys.version_info[:2] >= (3, 9):
  1476. @_TypeAliasForm
  1477. def Concatenate(self, parameters):
  1478. """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
  1479. higher order function which adds, removes or transforms parameters of a
  1480. callable.
  1481. For example::
  1482. Callable[Concatenate[int, P], int]
  1483. See PEP 612 for detailed information.
  1484. """
  1485. return _concatenate_getitem(self, parameters)
  1486. # 3.7-8
  1487. elif sys.version_info[:2] >= (3, 7):
  1488. class _ConcatenateForm(typing._SpecialForm, _root=True):
  1489. def __repr__(self):
  1490. return 'typing_extensions.' + self._name
  1491. def __getitem__(self, parameters):
  1492. return _concatenate_getitem(self, parameters)
  1493. Concatenate = _ConcatenateForm(
  1494. 'Concatenate',
  1495. doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
  1496. higher order function which adds, removes or transforms parameters of a
  1497. callable.
  1498. For example::
  1499. Callable[Concatenate[int, P], int]
  1500. See PEP 612 for detailed information.
  1501. """)
  1502. # 3.6
  1503. else:
  1504. class _ConcatenateAliasMeta(typing.TypingMeta):
  1505. """Metaclass for Concatenate."""
  1506. def __repr__(self):
  1507. return 'typing_extensions.Concatenate'
  1508. class _ConcatenateAliasBase(typing._FinalTypingBase,
  1509. metaclass=_ConcatenateAliasMeta,
  1510. _root=True):
  1511. """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
  1512. higher order function which adds, removes or transforms parameters of a
  1513. callable.
  1514. For example::
  1515. Callable[Concatenate[int, P], int]
  1516. See PEP 612 for detailed information.
  1517. """
  1518. __slots__ = ()
  1519. def __instancecheck__(self, obj):
  1520. raise TypeError("Concatenate cannot be used with isinstance().")
  1521. def __subclasscheck__(self, cls):
  1522. raise TypeError("Concatenate cannot be used with issubclass().")
  1523. def __repr__(self):
  1524. return 'typing_extensions.Concatenate'
  1525. def __getitem__(self, parameters):
  1526. return _concatenate_getitem(self, parameters)
  1527. Concatenate = _ConcatenateAliasBase(_root=True)
  1528. # 3.10+
  1529. if hasattr(typing, 'TypeGuard'):
  1530. TypeGuard = typing.TypeGuard
  1531. # 3.9
  1532. elif sys.version_info[:2] >= (3, 9):
  1533. class _TypeGuardForm(typing._SpecialForm, _root=True):
  1534. def __repr__(self):
  1535. return 'typing_extensions.' + self._name
  1536. @_TypeGuardForm
  1537. def TypeGuard(self, parameters):
  1538. """Special typing form used to annotate the return type of a user-defined
  1539. type guard function. ``TypeGuard`` only accepts a single type argument.
  1540. At runtime, functions marked this way should return a boolean.
  1541. ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
  1542. type checkers to determine a more precise type of an expression within a
  1543. program's code flow. Usually type narrowing is done by analyzing
  1544. conditional code flow and applying the narrowing to a block of code. The
  1545. conditional expression here is sometimes referred to as a "type guard".
  1546. Sometimes it would be convenient to use a user-defined boolean function
  1547. as a type guard. Such a function should use ``TypeGuard[...]`` as its
  1548. return type to alert static type checkers to this intention.
  1549. Using ``-> TypeGuard`` tells the static type checker that for a given
  1550. function:
  1551. 1. The return value is a boolean.
  1552. 2. If the return value is ``True``, the type of its argument
  1553. is the type inside ``TypeGuard``.
  1554. For example::
  1555. def is_str(val: Union[str, float]):
  1556. # "isinstance" type guard
  1557. if isinstance(val, str):
  1558. # Type of ``val`` is narrowed to ``str``
  1559. ...
  1560. else:
  1561. # Else, type of ``val`` is narrowed to ``float``.
  1562. ...
  1563. Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
  1564. form of ``TypeA`` (it can even be a wider form) and this may lead to
  1565. type-unsafe results. The main reason is to allow for things like
  1566. narrowing ``List[object]`` to ``List[str]`` even though the latter is not
  1567. a subtype of the former, since ``List`` is invariant. The responsibility of
  1568. writing type-safe type guards is left to the user.
  1569. ``TypeGuard`` also works with type variables. For more information, see
  1570. PEP 647 (User-Defined Type Guards).
  1571. """
  1572. item = typing._type_check(parameters, f'{self} accepts only single type.')
  1573. return typing._GenericAlias(self, (item,))
  1574. # 3.7-3.8
  1575. elif sys.version_info[:2] >= (3, 7):
  1576. class _TypeGuardForm(typing._SpecialForm, _root=True):
  1577. def __repr__(self):
  1578. return 'typing_extensions.' + self._name
  1579. def __getitem__(self, parameters):
  1580. item = typing._type_check(parameters,
  1581. f'{self._name} accepts only a single type')
  1582. return typing._GenericAlias(self, (item,))
  1583. TypeGuard = _TypeGuardForm(
  1584. 'TypeGuard',
  1585. doc="""Special typing form used to annotate the return type of a user-defined
  1586. type guard function. ``TypeGuard`` only accepts a single type argument.
  1587. At runtime, functions marked this way should return a boolean.
  1588. ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
  1589. type checkers to determine a more precise type of an expression within a
  1590. program's code flow. Usually type narrowing is done by analyzing
  1591. conditional code flow and applying the narrowing to a block of code. The
  1592. conditional expression here is sometimes referred to as a "type guard".
  1593. Sometimes it would be convenient to use a user-defined boolean function
  1594. as a type guard. Such a function should use ``TypeGuard[...]`` as its
  1595. return type to alert static type checkers to this intention.
  1596. Using ``-> TypeGuard`` tells the static type checker that for a given
  1597. function:
  1598. 1. The return value is a boolean.
  1599. 2. If the return value is ``True``, the type of its argument
  1600. is the type inside ``TypeGuard``.
  1601. For example::
  1602. def is_str(val: Union[str, float]):
  1603. # "isinstance" type guard
  1604. if isinstance(val, str):
  1605. # Type of ``val`` is narrowed to ``str``
  1606. ...
  1607. else:
  1608. # Else, type of ``val`` is narrowed to ``float``.
  1609. ...
  1610. Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
  1611. form of ``TypeA`` (it can even be a wider form) and this may lead to
  1612. type-unsafe results. The main reason is to allow for things like
  1613. narrowing ``List[object]`` to ``List[str]`` even though the latter is not
  1614. a subtype of the former, since ``List`` is invariant. The responsibility of
  1615. writing type-safe type guards is left to the user.
  1616. ``TypeGuard`` also works with type variables. For more information, see
  1617. PEP 647 (User-Defined Type Guards).
  1618. """)
  1619. # 3.6
  1620. else:
  1621. class _TypeGuard(typing._FinalTypingBase, _root=True):
  1622. """Special typing form used to annotate the return type of a user-defined
  1623. type guard function. ``TypeGuard`` only accepts a single type argument.
  1624. At runtime, functions marked this way should return a boolean.
  1625. ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
  1626. type checkers to determine a more precise type of an expression within a
  1627. program's code flow. Usually type narrowing is done by analyzing
  1628. conditional code flow and applying the narrowing to a block of code. The
  1629. conditional expression here is sometimes referred to as a "type guard".
  1630. Sometimes it would be convenient to use a user-defined boolean function
  1631. as a type guard. Such a function should use ``TypeGuard[...]`` as its
  1632. return type to alert static type checkers to this intention.
  1633. Using ``-> TypeGuard`` tells the static type checker that for a given
  1634. function:
  1635. 1. The return value is a boolean.
  1636. 2. If the return value is ``True``, the type of its argument
  1637. is the type inside ``TypeGuard``.
  1638. For example::
  1639. def is_str(val: Union[str, float]):
  1640. # "isinstance" type guard
  1641. if isinstance(val, str):
  1642. # Type of ``val`` is narrowed to ``str``
  1643. ...
  1644. else:
  1645. # Else, type of ``val`` is narrowed to ``float``.
  1646. ...
  1647. Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
  1648. form of ``TypeA`` (it can even be a wider form) and this may lead to
  1649. type-unsafe results. The main reason is to allow for things like
  1650. narrowing ``List[object]`` to ``List[str]`` even though the latter is not
  1651. a subtype of the former, since ``List`` is invariant. The responsibility of
  1652. writing type-safe type guards is left to the user.
  1653. ``TypeGuard`` also works with type variables. For more information, see
  1654. PEP 647 (User-Defined Type Guards).
  1655. """
  1656. __slots__ = ('__type__',)
  1657. def __init__(self, tp=None, **kwds):
  1658. self.__type__ = tp
  1659. def __getitem__(self, item):
  1660. cls = type(self)
  1661. if self.__type__ is None:
  1662. return cls(typing._type_check(item,
  1663. f'{cls.__name__[1:]} accepts only a single type.'),
  1664. _root=True)
  1665. raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')
  1666. def _eval_type(self, globalns, localns):
  1667. new_tp = typing._eval_type(self.__type__, globalns, localns)
  1668. if new_tp == self.__type__:
  1669. return self
  1670. return type(self)(new_tp, _root=True)
  1671. def __repr__(self):
  1672. r = super().__repr__()
  1673. if self.__type__ is not None:
  1674. r += f'[{typing._type_repr(self.__type__)}]'
  1675. return r
  1676. def __hash__(self):
  1677. return hash((type(self).__name__, self.__type__))
  1678. def __eq__(self, other):
  1679. if not isinstance(other, _TypeGuard):
  1680. return NotImplemented
  1681. if self.__type__ is not None:
  1682. return self.__type__ == other.__type__
  1683. return self is other
  1684. TypeGuard = _TypeGuard(_root=True)
  1685. if hasattr(typing, "Self"):
  1686. Self = typing.Self
  1687. elif sys.version_info[:2] >= (3, 7):
  1688. # Vendored from cpython typing._SpecialFrom
  1689. class _SpecialForm(typing._Final, _root=True):
  1690. __slots__ = ('_name', '__doc__', '_getitem')
  1691. def __init__(self, getitem):
  1692. self._getitem = getitem
  1693. self._name = getitem.__name__
  1694. self.__doc__ = getitem.__doc__
  1695. def __getattr__(self, item):
  1696. if item in {'__name__', '__qualname__'}:
  1697. return self._name
  1698. raise AttributeError(item)
  1699. def __mro_entries__(self, bases):
  1700. raise TypeError(f"Cannot subclass {self!r}")
  1701. def __repr__(self):
  1702. return f'typing_extensions.{self._name}'
  1703. def __reduce__(self):
  1704. return self._name
  1705. def __call__(self, *args, **kwds):
  1706. raise TypeError(f"Cannot instantiate {self!r}")
  1707. def __or__(self, other):
  1708. return typing.Union[self, other]
  1709. def __ror__(self, other):
  1710. return typing.Union[other, self]
  1711. def __instancecheck__(self, obj):
  1712. raise TypeError(f"{self} cannot be used with isinstance()")
  1713. def __subclasscheck__(self, cls):
  1714. raise TypeError(f"{self} cannot be used with issubclass()")
  1715. @typing._tp_cache
  1716. def __getitem__(self, parameters):
  1717. return self._getitem(self, parameters)
  1718. @_SpecialForm
  1719. def Self(self, params):
  1720. """Used to spell the type of "self" in classes.
  1721. Example::
  1722. from typing import Self
  1723. class ReturnsSelf:
  1724. def parse(self, data: bytes) -> Self:
  1725. ...
  1726. return self
  1727. """
  1728. raise TypeError(f"{self} is not subscriptable")
  1729. else:
  1730. class _Self(typing._FinalTypingBase, _root=True):
  1731. """Used to spell the type of "self" in classes.
  1732. Example::
  1733. from typing import Self
  1734. class ReturnsSelf:
  1735. def parse(self, data: bytes) -> Self:
  1736. ...
  1737. return self
  1738. """
  1739. __slots__ = ()
  1740. def __instancecheck__(self, obj):
  1741. raise TypeError(f"{self} cannot be used with isinstance().")
  1742. def __subclasscheck__(self, cls):
  1743. raise TypeError(f"{self} cannot be used with issubclass().")
  1744. Self = _Self(_root=True)
  1745. if hasattr(typing, 'Required'):
  1746. Required = typing.Required
  1747. NotRequired = typing.NotRequired
  1748. elif sys.version_info[:2] >= (3, 9):
  1749. class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
  1750. def __repr__(self):
  1751. return 'typing_extensions.' + self._name
  1752. @_ExtensionsSpecialForm
  1753. def Required(self, parameters):
  1754. """A special typing construct to mark a key of a total=False TypedDict
  1755. as required. For example:
  1756. class Movie(TypedDict, total=False):
  1757. title: Required[str]
  1758. year: int
  1759. m = Movie(
  1760. title='The Matrix', # typechecker error if key is omitted
  1761. year=1999,
  1762. )
  1763. There is no runtime checking that a required key is actually provided
  1764. when instantiating a related TypedDict.
  1765. """
  1766. item = typing._type_check(parameters, f'{self._name} accepts only single type')
  1767. return typing._GenericAlias(self, (item,))
  1768. @_ExtensionsSpecialForm
  1769. def NotRequired(self, parameters):
  1770. """A special typing construct to mark a key of a TypedDict as
  1771. potentially missing. For example:
  1772. class Movie(TypedDict):
  1773. title: str
  1774. year: NotRequired[int]
  1775. m = Movie(
  1776. title='The Matrix', # typechecker error if key is omitted
  1777. year=1999,
  1778. )
  1779. """
  1780. item = typing._type_check(parameters, f'{self._name} accepts only single type')
  1781. return typing._GenericAlias(self, (item,))
  1782. elif sys.version_info[:2] >= (3, 7):
  1783. class _RequiredForm(typing._SpecialForm, _root=True):
  1784. def __repr__(self):
  1785. return 'typing_extensions.' + self._name
  1786. def __getitem__(self, parameters):
  1787. item = typing._type_check(parameters,
  1788. '{} accepts only single type'.format(self._name))
  1789. return typing._GenericAlias(self, (item,))
  1790. Required = _RequiredForm(
  1791. 'Required',
  1792. doc="""A special typing construct to mark a key of a total=False TypedDict
  1793. as required. For example:
  1794. class Movie(TypedDict, total=False):
  1795. title: Required[str]
  1796. year: int
  1797. m = Movie(
  1798. title='The Matrix', # typechecker error if key is omitted
  1799. year=1999,
  1800. )
  1801. There is no runtime checking that a required key is actually provided
  1802. when instantiating a related TypedDict.
  1803. """)
  1804. NotRequired = _RequiredForm(
  1805. 'NotRequired',
  1806. doc="""A special typing construct to mark a key of a TypedDict as
  1807. potentially missing. For example:
  1808. class Movie(TypedDict):
  1809. title: str
  1810. year: NotRequired[int]
  1811. m = Movie(
  1812. title='The Matrix', # typechecker error if key is omitted
  1813. year=1999,
  1814. )
  1815. """)
  1816. else:
  1817. # NOTE: Modeled after _Final's implementation when _FinalTypingBase available
  1818. class _MaybeRequired(typing._FinalTypingBase, _root=True):
  1819. __slots__ = ('__type__',)
  1820. def __init__(self, tp=None, **kwds):
  1821. self.__type__ = tp
  1822. def __getitem__(self, item):
  1823. cls = type(self)
  1824. if self.__type__ is None:
  1825. return cls(typing._type_check(item,
  1826. '{} accepts only single type.'.format(cls.__name__[1:])),
  1827. _root=True)
  1828. raise TypeError('{} cannot be further subscripted'
  1829. .format(cls.__name__[1:]))
  1830. def _eval_type(self, globalns, localns):
  1831. new_tp = typing._eval_type(self.__type__, globalns, localns)
  1832. if new_tp == self.__type__:
  1833. return self
  1834. return type(self)(new_tp, _root=True)
  1835. def __repr__(self):
  1836. r = super().__repr__()
  1837. if self.__type__ is not None:
  1838. r += '[{}]'.format(typing._type_repr(self.__type__))
  1839. return r
  1840. def __hash__(self):
  1841. return hash((type(self).__name__, self.__type__))
  1842. def __eq__(self, other):
  1843. if not isinstance(other, type(self)):
  1844. return NotImplemented
  1845. if self.__type__ is not None:
  1846. return self.__type__ == other.__type__
  1847. return self is other
  1848. class _Required(_MaybeRequired, _root=True):
  1849. """A special typing construct to mark a key of a total=False TypedDict
  1850. as required. For example:
  1851. class Movie(TypedDict, total=False):
  1852. title: Required[str]
  1853. year: int
  1854. m = Movie(
  1855. title='The Matrix', # typechecker error if key is omitted
  1856. year=1999,
  1857. )
  1858. There is no runtime checking that a required key is actually provided
  1859. when instantiating a related TypedDict.
  1860. """
  1861. class _NotRequired(_MaybeRequired, _root=True):
  1862. """A special typing construct to mark a key of a TypedDict as
  1863. potentially missing. For example:
  1864. class Movie(TypedDict):
  1865. title: str
  1866. year: NotRequired[int]
  1867. m = Movie(
  1868. title='The Matrix', # typechecker error if key is omitted
  1869. year=1999,
  1870. )
  1871. """
  1872. Required = _Required(_root=True)
  1873. NotRequired = _NotRequired(_root=True)