typing_extensions.py 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936
  1. import abc
  2. import collections
  3. import contextlib
  4. import sys
  5. import typing
  6. import collections.abc as collections_abc
  7. import operator
  8. # After PEP 560, internal typing API was substantially reworked.
  9. # This is especially important for Protocol class which uses internal APIs
  10. # quite extensivelly.
  11. PEP_560 = sys.version_info[:3] >= (3, 7, 0)
  12. # These are used by Protocol implementation
  13. # We use internal typing helpers here, but this significantly reduces
  14. # code duplication. (Also this is only until Protocol is in typing.)
  15. from typing import Generic, Callable, TypeVar, Tuple
  16. if PEP_560:
  17. GenericMeta = TypingMeta = type
  18. else:
  19. from typing import GenericMeta, TypingMeta
  20. OLD_GENERICS = False
  21. try:
  22. from typing import _type_vars, _next_in_mro, _type_check
  23. except ImportError:
  24. OLD_GENERICS = True
  25. try:
  26. from typing import _subs_tree
  27. SUBS_TREE = True
  28. except ImportError:
  29. SUBS_TREE = False
  30. try:
  31. from typing import _tp_cache
  32. except ImportError:
  33. _tp_cache = lambda x: x
  34. try:
  35. from typing import _TypingEllipsis, _TypingEmpty
  36. except ImportError:
  37. class _TypingEllipsis: pass
  38. class _TypingEmpty: pass
  39. # The two functions below are copies of typing internal helpers.
  40. # They are needed by _ProtocolMeta
  41. def _no_slots_copy(dct):
  42. dict_copy = dict(dct)
  43. if '__slots__' in dict_copy:
  44. for slot in dict_copy['__slots__']:
  45. dict_copy.pop(slot, None)
  46. return dict_copy
  47. def _check_generic(cls, parameters):
  48. if not cls.__parameters__:
  49. raise TypeError("%s is not a generic class" % repr(cls))
  50. alen = len(parameters)
  51. elen = len(cls.__parameters__)
  52. if alen != elen:
  53. raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
  54. ("many" if alen > elen else "few", repr(cls), alen, elen))
  55. if hasattr(typing, '_generic_new'):
  56. _generic_new = typing._generic_new
  57. else:
  58. # Note: The '_generic_new(...)' function is used as a part of the
  59. # process of creating a generic type and was added to the typing module
  60. # as of Python 3.5.3.
  61. #
  62. # We've defined '_generic_new(...)' below to exactly match the behavior
  63. # implemented in older versions of 'typing' bundled with Python 3.5.0 to
  64. # 3.5.2. This helps eliminate redundancy when defining collection types
  65. # like 'Deque' later.
  66. #
  67. # See https://github.com/python/typing/pull/308 for more details -- in
  68. # particular, compare and contrast the definition of types like
  69. # 'typing.List' before and after the merge.
  70. def _generic_new(base_cls, cls, *args, **kwargs):
  71. return base_cls.__new__(cls, *args, **kwargs)
  72. # See https://github.com/python/typing/pull/439
  73. if hasattr(typing, '_geqv'):
  74. from typing import _geqv
  75. _geqv_defined = True
  76. else:
  77. _geqv = None
  78. _geqv_defined = False
  79. if sys.version_info[:2] >= (3, 6):
  80. import _collections_abc
  81. _check_methods_in_mro = _collections_abc._check_methods
  82. else:
  83. def _check_methods_in_mro(C, *methods):
  84. mro = C.__mro__
  85. for method in methods:
  86. for B in mro:
  87. if method in B.__dict__:
  88. if B.__dict__[method] is None:
  89. return NotImplemented
  90. break
  91. else:
  92. return NotImplemented
  93. return True
  94. # Please keep __all__ alphabetized within each category.
  95. __all__ = [
  96. # Super-special typing primitives.
  97. 'ClassVar',
  98. 'Final',
  99. 'Type',
  100. # ABCs (from collections.abc).
  101. # The following are added depending on presence
  102. # of their non-generic counterparts in stdlib:
  103. # 'Awaitable',
  104. # 'AsyncIterator',
  105. # 'AsyncIterable',
  106. # 'Coroutine',
  107. # 'AsyncGenerator',
  108. # 'AsyncContextManager',
  109. # 'ChainMap',
  110. # Concrete collection types.
  111. 'ContextManager',
  112. 'Counter',
  113. 'Deque',
  114. 'DefaultDict',
  115. 'TypedDict',
  116. # One-off things.
  117. 'final',
  118. 'IntVar',
  119. 'Literal',
  120. 'NewType',
  121. 'overload',
  122. 'Text',
  123. 'TYPE_CHECKING',
  124. ]
  125. # Annotated relies on substitution trees of pep 560. It will not work for
  126. # versions of typing older than 3.5.3
  127. HAVE_ANNOTATED = PEP_560 or SUBS_TREE
  128. if PEP_560:
  129. __all__.append("get_type_hints")
  130. if HAVE_ANNOTATED:
  131. __all__.append("Annotated")
  132. # Protocols are hard to backport to the original version of typing 3.5.0
  133. HAVE_PROTOCOLS = sys.version_info[:3] != (3, 5, 0)
  134. if HAVE_PROTOCOLS:
  135. __all__.extend(['Protocol', 'runtime', 'runtime_checkable'])
  136. # TODO
  137. if hasattr(typing, 'NoReturn'):
  138. NoReturn = typing.NoReturn
  139. elif hasattr(typing, '_FinalTypingBase'):
  140. class _NoReturn(typing._FinalTypingBase, _root=True):
  141. """Special type indicating functions that never return.
  142. Example::
  143. from typing import NoReturn
  144. def stop() -> NoReturn:
  145. raise Exception('no way')
  146. This type is invalid in other positions, e.g., ``List[NoReturn]``
  147. will fail in static type checkers.
  148. """
  149. __slots__ = ()
  150. def __instancecheck__(self, obj):
  151. raise TypeError("NoReturn cannot be used with isinstance().")
  152. def __subclasscheck__(self, cls):
  153. raise TypeError("NoReturn cannot be used with issubclass().")
  154. NoReturn = _NoReturn(_root=True)
  155. else:
  156. class _NoReturnMeta(typing.TypingMeta):
  157. """Metaclass for NoReturn"""
  158. def __new__(cls, name, bases, namespace, _root=False):
  159. return super().__new__(cls, name, bases, namespace, _root=_root)
  160. def __instancecheck__(self, obj):
  161. raise TypeError("NoReturn cannot be used with isinstance().")
  162. def __subclasscheck__(self, cls):
  163. raise TypeError("NoReturn cannot be used with issubclass().")
  164. class NoReturn(typing.Final, metaclass=_NoReturnMeta, _root=True):
  165. """Special type indicating functions that never return.
  166. Example::
  167. from typing import NoReturn
  168. def stop() -> NoReturn:
  169. raise Exception('no way')
  170. This type is invalid in other positions, e.g., ``List[NoReturn]``
  171. will fail in static type checkers.
  172. """
  173. __slots__ = ()
  174. # Some unconstrained type variables. These are used by the container types.
  175. # (These are not for export.)
  176. T = typing.TypeVar('T') # Any type.
  177. KT = typing.TypeVar('KT') # Key type.
  178. VT = typing.TypeVar('VT') # Value type.
  179. T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
  180. V_co = typing.TypeVar('V_co', covariant=True) # Any type covariant containers.
  181. VT_co = typing.TypeVar('VT_co', covariant=True) # Value type covariant containers.
  182. T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
  183. if hasattr(typing, 'ClassVar'):
  184. ClassVar = typing.ClassVar
  185. elif hasattr(typing, '_FinalTypingBase'):
  186. class _ClassVar(typing._FinalTypingBase, _root=True):
  187. """Special type construct to mark class variables.
  188. An annotation wrapped in ClassVar indicates that a given
  189. attribute is intended to be used as a class variable and
  190. should not be set on instances of that class. Usage::
  191. class Starship:
  192. stats: ClassVar[Dict[str, int]] = {} # class variable
  193. damage: int = 10 # instance variable
  194. ClassVar accepts only types and cannot be further subscribed.
  195. Note that ClassVar is not a class itself, and should not
  196. be used with isinstance() or issubclass().
  197. """
  198. __slots__ = ('__type__',)
  199. def __init__(self, tp=None, **kwds):
  200. self.__type__ = tp
  201. def __getitem__(self, item):
  202. cls = type(self)
  203. if self.__type__ is None:
  204. return cls(typing._type_check(item,
  205. '{} accepts only single type.'.format(cls.__name__[1:])),
  206. _root=True)
  207. raise TypeError('{} cannot be further subscripted'
  208. .format(cls.__name__[1:]))
  209. def _eval_type(self, globalns, localns):
  210. new_tp = typing._eval_type(self.__type__, globalns, localns)
  211. if new_tp == self.__type__:
  212. return self
  213. return type(self)(new_tp, _root=True)
  214. def __repr__(self):
  215. r = super().__repr__()
  216. if self.__type__ is not None:
  217. r += '[{}]'.format(typing._type_repr(self.__type__))
  218. return r
  219. def __hash__(self):
  220. return hash((type(self).__name__, self.__type__))
  221. def __eq__(self, other):
  222. if not isinstance(other, _ClassVar):
  223. return NotImplemented
  224. if self.__type__ is not None:
  225. return self.__type__ == other.__type__
  226. return self is other
  227. ClassVar = _ClassVar(_root=True)
  228. else:
  229. class _ClassVarMeta(typing.TypingMeta):
  230. """Metaclass for ClassVar"""
  231. def __new__(cls, name, bases, namespace, tp=None, _root=False):
  232. self = super().__new__(cls, name, bases, namespace, _root=_root)
  233. if tp is not None:
  234. self.__type__ = tp
  235. return self
  236. def __instancecheck__(self, obj):
  237. raise TypeError("ClassVar cannot be used with isinstance().")
  238. def __subclasscheck__(self, cls):
  239. raise TypeError("ClassVar cannot be used with issubclass().")
  240. def __getitem__(self, item):
  241. cls = type(self)
  242. if self.__type__ is not None:
  243. raise TypeError('{} cannot be further subscripted'
  244. .format(cls.__name__[1:]))
  245. param = typing._type_check(
  246. item,
  247. '{} accepts only single type.'.format(cls.__name__[1:]))
  248. return cls(self.__name__, self.__bases__,
  249. dict(self.__dict__), tp=param, _root=True)
  250. def _eval_type(self, globalns, localns):
  251. new_tp = typing._eval_type(self.__type__, globalns, localns)
  252. if new_tp == self.__type__:
  253. return self
  254. return type(self)(self.__name__, self.__bases__,
  255. dict(self.__dict__), tp=self.__type__,
  256. _root=True)
  257. def __repr__(self):
  258. r = super().__repr__()
  259. if self.__type__ is not None:
  260. r += '[{}]'.format(typing._type_repr(self.__type__))
  261. return r
  262. def __hash__(self):
  263. return hash((type(self).__name__, self.__type__))
  264. def __eq__(self, other):
  265. if not isinstance(other, ClassVar):
  266. return NotImplemented
  267. if self.__type__ is not None:
  268. return self.__type__ == other.__type__
  269. return self is other
  270. class ClassVar(typing.Final, metaclass=_ClassVarMeta, _root=True):
  271. """Special type construct to mark class variables.
  272. An annotation wrapped in ClassVar indicates that a given
  273. attribute is intended to be used as a class variable and
  274. should not be set on instances of that class. Usage::
  275. class Starship:
  276. stats: ClassVar[Dict[str, int]] = {} # class variable
  277. damage: int = 10 # instance variable
  278. ClassVar accepts only types and cannot be further subscribed.
  279. Note that ClassVar is not a class itself, and should not
  280. be used with isinstance() or issubclass().
  281. """
  282. __type__ = None
  283. # On older versions of typing there is an internal class named "Final".
  284. if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
  285. Final = typing.Final
  286. elif sys.version_info[:2] >= (3, 7):
  287. class _FinalForm(typing._SpecialForm, _root=True):
  288. def __repr__(self):
  289. return 'typing_extensions.' + self._name
  290. def __getitem__(self, parameters):
  291. item = typing._type_check(parameters,
  292. '{} accepts only single type'.format(self._name))
  293. return _GenericAlias(self, (item,))
  294. Final = _FinalForm('Final', doc=
  295. """A special typing construct to indicate that a name
  296. cannot be re-assigned or overridden in a subclass.
  297. For example:
  298. MAX_SIZE: Final = 9000
  299. MAX_SIZE += 1 # Error reported by type checker
  300. class Connection:
  301. TIMEOUT: Final[int] = 10
  302. class FastConnector(Connection):
  303. TIMEOUT = 1 # Error reported by type checker
  304. There is no runtime checking of these properties.
  305. """)
  306. elif hasattr(typing, '_FinalTypingBase'):
  307. class _Final(typing._FinalTypingBase, _root=True):
  308. """A special typing construct to indicate that a name
  309. cannot be re-assigned or overridden in a subclass.
  310. For example:
  311. MAX_SIZE: Final = 9000
  312. MAX_SIZE += 1 # Error reported by type checker
  313. class Connection:
  314. TIMEOUT: Final[int] = 10
  315. class FastConnector(Connection):
  316. TIMEOUT = 1 # Error reported by type checker
  317. There is no runtime checking of these properties.
  318. """
  319. __slots__ = ('__type__',)
  320. def __init__(self, tp=None, **kwds):
  321. self.__type__ = tp
  322. def __getitem__(self, item):
  323. cls = type(self)
  324. if self.__type__ is None:
  325. return cls(typing._type_check(item,
  326. '{} accepts only single type.'.format(cls.__name__[1:])),
  327. _root=True)
  328. raise TypeError('{} cannot be further subscripted'
  329. .format(cls.__name__[1:]))
  330. def _eval_type(self, globalns, localns):
  331. new_tp = typing._eval_type(self.__type__, globalns, localns)
  332. if new_tp == self.__type__:
  333. return self
  334. return type(self)(new_tp, _root=True)
  335. def __repr__(self):
  336. r = super().__repr__()
  337. if self.__type__ is not None:
  338. r += '[{}]'.format(typing._type_repr(self.__type__))
  339. return r
  340. def __hash__(self):
  341. return hash((type(self).__name__, self.__type__))
  342. def __eq__(self, other):
  343. if not isinstance(other, _Final):
  344. return NotImplemented
  345. if self.__type__ is not None:
  346. return self.__type__ == other.__type__
  347. return self is other
  348. Final = _Final(_root=True)
  349. else:
  350. class _FinalMeta(typing.TypingMeta):
  351. """Metaclass for Final"""
  352. def __new__(cls, name, bases, namespace, tp=None, _root=False):
  353. self = super().__new__(cls, name, bases, namespace, _root=_root)
  354. if tp is not None:
  355. self.__type__ = tp
  356. return self
  357. def __instancecheck__(self, obj):
  358. raise TypeError("Final cannot be used with isinstance().")
  359. def __subclasscheck__(self, cls):
  360. raise TypeError("Final cannot be used with issubclass().")
  361. def __getitem__(self, item):
  362. cls = type(self)
  363. if self.__type__ is not None:
  364. raise TypeError('{} cannot be further subscripted'
  365. .format(cls.__name__[1:]))
  366. param = typing._type_check(
  367. item,
  368. '{} accepts only single type.'.format(cls.__name__[1:]))
  369. return cls(self.__name__, self.__bases__,
  370. dict(self.__dict__), tp=param, _root=True)
  371. def _eval_type(self, globalns, localns):
  372. new_tp = typing._eval_type(self.__type__, globalns, localns)
  373. if new_tp == self.__type__:
  374. return self
  375. return type(self)(self.__name__, self.__bases__,
  376. dict(self.__dict__), tp=self.__type__,
  377. _root=True)
  378. def __repr__(self):
  379. r = super().__repr__()
  380. if self.__type__ is not None:
  381. r += '[{}]'.format(typing._type_repr(self.__type__))
  382. return r
  383. def __hash__(self):
  384. return hash((type(self).__name__, self.__type__))
  385. def __eq__(self, other):
  386. if not isinstance(other, Final):
  387. return NotImplemented
  388. if self.__type__ is not None:
  389. return self.__type__ == other.__type__
  390. return self is other
  391. class Final(typing.Final, metaclass=_FinalMeta, _root=True):
  392. """A special typing construct to indicate that a name
  393. cannot be re-assigned or overridden in a subclass.
  394. For example:
  395. MAX_SIZE: Final = 9000
  396. MAX_SIZE += 1 # Error reported by type checker
  397. class Connection:
  398. TIMEOUT: Final[int] = 10
  399. class FastConnector(Connection):
  400. TIMEOUT = 1 # Error reported by type checker
  401. There is no runtime checking of these properties.
  402. """
  403. __type__ = None
  404. if hasattr(typing, 'final'):
  405. final = typing.final
  406. else:
  407. def final(f):
  408. """This decorator can be used to indicate to type checkers that
  409. the decorated method cannot be overridden, and decorated class
  410. cannot be subclassed. For example:
  411. class Base:
  412. @final
  413. def done(self) -> None:
  414. ...
  415. class Sub(Base):
  416. def done(self) -> None: # Error reported by type checker
  417. ...
  418. @final
  419. class Leaf:
  420. ...
  421. class Other(Leaf): # Error reported by type checker
  422. ...
  423. There is no runtime checking of these properties.
  424. """
  425. return f
  426. def IntVar(name):
  427. return TypeVar(name)
  428. if hasattr(typing, 'Literal'):
  429. Literal = typing.Literal
  430. elif sys.version_info[:2] >= (3, 7):
  431. class _LiteralForm(typing._SpecialForm, _root=True):
  432. def __repr__(self):
  433. return 'typing_extensions.' + self._name
  434. def __getitem__(self, parameters):
  435. return _GenericAlias(self, parameters)
  436. Literal = _LiteralForm('Literal', doc=
  437. """A type that can be used to indicate to type checkers that the
  438. corresponding value has a value literally equivalent to the
  439. provided parameter. For example:
  440. var: Literal[4] = 4
  441. The type checker understands that 'var' is literally equal to the
  442. value 4 and no other value.
  443. Literal[...] cannot be subclassed. There is no runtime checking
  444. verifying that the parameter is actually a value instead of a type.
  445. """)
  446. elif hasattr(typing, '_FinalTypingBase'):
  447. class _Literal(typing._FinalTypingBase, _root=True):
  448. """A type that can be used to indicate to type checkers that the
  449. corresponding value has a value literally equivalent to the
  450. provided parameter. For example:
  451. var: Literal[4] = 4
  452. The type checker understands that 'var' is literally equal to the
  453. value 4 and no other value.
  454. Literal[...] cannot be subclassed. There is no runtime checking
  455. verifying that the parameter is actually a value instead of a type.
  456. """
  457. __slots__ = ('__values__',)
  458. def __init__(self, values=None, **kwds):
  459. self.__values__ = values
  460. def __getitem__(self, values):
  461. cls = type(self)
  462. if self.__values__ is None:
  463. if not isinstance(values, tuple):
  464. values = (values,)
  465. return cls(values, _root=True)
  466. raise TypeError('{} cannot be further subscripted'
  467. .format(cls.__name__[1:]))
  468. def _eval_type(self, globalns, localns):
  469. return self
  470. def __repr__(self):
  471. r = super().__repr__()
  472. if self.__values__ is not None:
  473. r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__)))
  474. return r
  475. def __hash__(self):
  476. return hash((type(self).__name__, self.__values__))
  477. def __eq__(self, other):
  478. if not isinstance(other, _Literal):
  479. return NotImplemented
  480. if self.__values__ is not None:
  481. return self.__values__ == other.__values__
  482. return self is other
  483. Literal = _Literal(_root=True)
  484. else:
  485. class _LiteralMeta(typing.TypingMeta):
  486. """Metaclass for Literal"""
  487. def __new__(cls, name, bases, namespace, values=None, _root=False):
  488. self = super().__new__(cls, name, bases, namespace, _root=_root)
  489. if values is not None:
  490. self.__values__ = values
  491. return self
  492. def __instancecheck__(self, obj):
  493. raise TypeError("Literal cannot be used with isinstance().")
  494. def __subclasscheck__(self, cls):
  495. raise TypeError("Literal cannot be used with issubclass().")
  496. def __getitem__(self, item):
  497. cls = type(self)
  498. if self.__values__ is not None:
  499. raise TypeError('{} cannot be further subscripted'
  500. .format(cls.__name__[1:]))
  501. if not isinstance(item, tuple):
  502. item = (item,)
  503. return cls(self.__name__, self.__bases__,
  504. dict(self.__dict__), values=item, _root=True)
  505. def _eval_type(self, globalns, localns):
  506. return self
  507. def __repr__(self):
  508. r = super().__repr__()
  509. if self.__values__ is not None:
  510. r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__)))
  511. return r
  512. def __hash__(self):
  513. return hash((type(self).__name__, self.__values__))
  514. def __eq__(self, other):
  515. if not isinstance(other, Literal):
  516. return NotImplemented
  517. if self.__values__ is not None:
  518. return self.__values__ == other.__values__
  519. return self is other
  520. class Literal(typing.Final, metaclass=_LiteralMeta, _root=True):
  521. """A type that can be used to indicate to type checkers that the
  522. corresponding value has a value literally equivalent to the
  523. provided parameter. For example:
  524. var: Literal[4] = 4
  525. The type checker understands that 'var' is literally equal to the
  526. value 4 and no other value.
  527. Literal[...] cannot be subclassed. There is no runtime checking
  528. verifying that the parameter is actually a value instead of a type.
  529. """
  530. __values__ = None
  531. def _overload_dummy(*args, **kwds):
  532. """Helper for @overload to raise when called."""
  533. raise NotImplementedError(
  534. "You should not call an overloaded function. "
  535. "A series of @overload-decorated functions "
  536. "outside a stub module should always be followed "
  537. "by an implementation that is not @overload-ed.")
  538. def overload(func):
  539. """Decorator for overloaded functions/methods.
  540. In a stub file, place two or more stub definitions for the same
  541. function in a row, each decorated with @overload. For example:
  542. @overload
  543. def utf8(value: None) -> None: ...
  544. @overload
  545. def utf8(value: bytes) -> bytes: ...
  546. @overload
  547. def utf8(value: str) -> bytes: ...
  548. In a non-stub file (i.e. a regular .py file), do the same but
  549. follow it with an implementation. The implementation should *not*
  550. be decorated with @overload. For example:
  551. @overload
  552. def utf8(value: None) -> None: ...
  553. @overload
  554. def utf8(value: bytes) -> bytes: ...
  555. @overload
  556. def utf8(value: str) -> bytes: ...
  557. def utf8(value):
  558. # implementation goes here
  559. """
  560. return _overload_dummy
  561. # This is not a real generic class. Don't use outside annotations.
  562. if hasattr(typing, 'Type'):
  563. Type = typing.Type
  564. else:
  565. # Internal type variable used for Type[].
  566. CT_co = typing.TypeVar('CT_co', covariant=True, bound=type)
  567. class Type(typing.Generic[CT_co], extra=type):
  568. """A special construct usable to annotate class objects.
  569. For example, suppose we have the following classes::
  570. class User: ... # Abstract base for User classes
  571. class BasicUser(User): ...
  572. class ProUser(User): ...
  573. class TeamUser(User): ...
  574. And a function that takes a class argument that's a subclass of
  575. User and returns an instance of the corresponding class::
  576. U = TypeVar('U', bound=User)
  577. def new_user(user_class: Type[U]) -> U:
  578. user = user_class()
  579. # (Here we could write the user object to a database)
  580. return user
  581. joe = new_user(BasicUser)
  582. At this point the type checker knows that joe has type BasicUser.
  583. """
  584. __slots__ = ()
  585. # Various ABCs mimicking those in collections.abc.
  586. # A few are simply re-exported for completeness.
  587. def _define_guard(type_name):
  588. """
  589. Returns True if the given type isn't defined in typing but
  590. is defined in collections_abc.
  591. Adds the type to __all__ if the collection is found in either
  592. typing or collection_abc.
  593. """
  594. if hasattr(typing, type_name):
  595. __all__.append(type_name)
  596. globals()[type_name] = getattr(typing, type_name)
  597. return False
  598. elif hasattr(collections_abc, type_name):
  599. __all__.append(type_name)
  600. return True
  601. else:
  602. return False
  603. class _ExtensionsGenericMeta(GenericMeta):
  604. def __subclasscheck__(self, subclass):
  605. """This mimics a more modern GenericMeta.__subclasscheck__() logic
  606. (that does not have problems with recursion) to work around interactions
  607. between collections, typing, and typing_extensions on older
  608. versions of Python, see https://github.com/python/typing/issues/501.
  609. """
  610. if sys.version_info[:3] >= (3, 5, 3) or sys.version_info[:3] < (3, 5, 0):
  611. if self.__origin__ is not None:
  612. if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
  613. raise TypeError("Parameterized generics cannot be used with class "
  614. "or instance checks")
  615. return False
  616. if not self.__extra__:
  617. return super().__subclasscheck__(subclass)
  618. res = self.__extra__.__subclasshook__(subclass)
  619. if res is not NotImplemented:
  620. return res
  621. if self.__extra__ in subclass.__mro__:
  622. return True
  623. for scls in self.__extra__.__subclasses__():
  624. if isinstance(scls, GenericMeta):
  625. continue
  626. if issubclass(subclass, scls):
  627. return True
  628. return False
  629. if _define_guard('Awaitable'):
  630. class Awaitable(typing.Generic[T_co], metaclass=_ExtensionsGenericMeta,
  631. extra=collections_abc.Awaitable):
  632. __slots__ = ()
  633. if _define_guard('Coroutine'):
  634. class Coroutine(Awaitable[V_co], typing.Generic[T_co, T_contra, V_co],
  635. metaclass=_ExtensionsGenericMeta,
  636. extra=collections_abc.Coroutine):
  637. __slots__ = ()
  638. if _define_guard('AsyncIterable'):
  639. class AsyncIterable(typing.Generic[T_co],
  640. metaclass=_ExtensionsGenericMeta,
  641. extra=collections_abc.AsyncIterable):
  642. __slots__ = ()
  643. if _define_guard('AsyncIterator'):
  644. class AsyncIterator(AsyncIterable[T_co],
  645. metaclass=_ExtensionsGenericMeta,
  646. extra=collections_abc.AsyncIterator):
  647. __slots__ = ()
  648. if hasattr(typing, 'Deque'):
  649. Deque = typing.Deque
  650. elif _geqv_defined:
  651. class Deque(collections.deque, typing.MutableSequence[T],
  652. metaclass=_ExtensionsGenericMeta,
  653. extra=collections.deque):
  654. __slots__ = ()
  655. def __new__(cls, *args, **kwds):
  656. if _geqv(cls, Deque):
  657. return collections.deque(*args, **kwds)
  658. return _generic_new(collections.deque, cls, *args, **kwds)
  659. else:
  660. class Deque(collections.deque, typing.MutableSequence[T],
  661. metaclass=_ExtensionsGenericMeta,
  662. extra=collections.deque):
  663. __slots__ = ()
  664. def __new__(cls, *args, **kwds):
  665. if cls._gorg is Deque:
  666. return collections.deque(*args, **kwds)
  667. return _generic_new(collections.deque, cls, *args, **kwds)
  668. if hasattr(typing, 'ContextManager'):
  669. ContextManager = typing.ContextManager
  670. elif hasattr(contextlib, 'AbstractContextManager'):
  671. class ContextManager(typing.Generic[T_co],
  672. metaclass=_ExtensionsGenericMeta,
  673. extra=contextlib.AbstractContextManager):
  674. __slots__ = ()
  675. else:
  676. class ContextManager(typing.Generic[T_co]):
  677. __slots__ = ()
  678. def __enter__(self):
  679. return self
  680. @abc.abstractmethod
  681. def __exit__(self, exc_type, exc_value, traceback):
  682. return None
  683. @classmethod
  684. def __subclasshook__(cls, C):
  685. if cls is ContextManager:
  686. # In Python 3.6+, it is possible to set a method to None to
  687. # explicitly indicate that the class does not implement an ABC
  688. # (https://bugs.python.org/issue25958), but we do not support
  689. # that pattern here because this fallback class is only used
  690. # in Python 3.5 and earlier.
  691. if (any("__enter__" in B.__dict__ for B in C.__mro__) and
  692. any("__exit__" in B.__dict__ for B in C.__mro__)):
  693. return True
  694. return NotImplemented
  695. if hasattr(typing, 'AsyncContextManager'):
  696. AsyncContextManager = typing.AsyncContextManager
  697. __all__.append('AsyncContextManager')
  698. elif hasattr(contextlib, 'AbstractAsyncContextManager'):
  699. class AsyncContextManager(typing.Generic[T_co],
  700. metaclass=_ExtensionsGenericMeta,
  701. extra=contextlib.AbstractAsyncContextManager):
  702. __slots__ = ()
  703. __all__.append('AsyncContextManager')
  704. elif sys.version_info[:2] >= (3, 5):
  705. exec("""
  706. class AsyncContextManager(typing.Generic[T_co]):
  707. __slots__ = ()
  708. async def __aenter__(self):
  709. return self
  710. @abc.abstractmethod
  711. async def __aexit__(self, exc_type, exc_value, traceback):
  712. return None
  713. @classmethod
  714. def __subclasshook__(cls, C):
  715. if cls is AsyncContextManager:
  716. return _check_methods_in_mro(C, "__aenter__", "__aexit__")
  717. return NotImplemented
  718. __all__.append('AsyncContextManager')
  719. """)
  720. if hasattr(typing, 'DefaultDict'):
  721. DefaultDict = typing.DefaultDict
  722. elif _geqv_defined:
  723. class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT],
  724. metaclass=_ExtensionsGenericMeta,
  725. extra=collections.defaultdict):
  726. __slots__ = ()
  727. def __new__(cls, *args, **kwds):
  728. if _geqv(cls, DefaultDict):
  729. return collections.defaultdict(*args, **kwds)
  730. return _generic_new(collections.defaultdict, cls, *args, **kwds)
  731. else:
  732. class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT],
  733. metaclass=_ExtensionsGenericMeta,
  734. extra=collections.defaultdict):
  735. __slots__ = ()
  736. def __new__(cls, *args, **kwds):
  737. if cls._gorg is DefaultDict:
  738. return collections.defaultdict(*args, **kwds)
  739. return _generic_new(collections.defaultdict, cls, *args, **kwds)
  740. if hasattr(typing, 'Counter'):
  741. Counter = typing.Counter
  742. elif (3, 5, 0) <= sys.version_info[:3] <= (3, 5, 1):
  743. assert _geqv_defined
  744. _TInt = typing.TypeVar('_TInt')
  745. class _CounterMeta(typing.GenericMeta):
  746. """Metaclass for Counter"""
  747. def __getitem__(self, item):
  748. return super().__getitem__((item, int))
  749. class Counter(collections.Counter,
  750. typing.Dict[T, int],
  751. metaclass=_CounterMeta,
  752. extra=collections.Counter):
  753. __slots__ = ()
  754. def __new__(cls, *args, **kwds):
  755. if _geqv(cls, Counter):
  756. return collections.Counter(*args, **kwds)
  757. return _generic_new(collections.Counter, cls, *args, **kwds)
  758. elif _geqv_defined:
  759. class Counter(collections.Counter,
  760. typing.Dict[T, int],
  761. metaclass=_ExtensionsGenericMeta, extra=collections.Counter):
  762. __slots__ = ()
  763. def __new__(cls, *args, **kwds):
  764. if _geqv(cls, Counter):
  765. return collections.Counter(*args, **kwds)
  766. return _generic_new(collections.Counter, cls, *args, **kwds)
  767. else:
  768. class Counter(collections.Counter,
  769. typing.Dict[T, int],
  770. metaclass=_ExtensionsGenericMeta, extra=collections.Counter):
  771. __slots__ = ()
  772. def __new__(cls, *args, **kwds):
  773. if cls._gorg is Counter:
  774. return collections.Counter(*args, **kwds)
  775. return _generic_new(collections.Counter, cls, *args, **kwds)
  776. if hasattr(typing, 'ChainMap'):
  777. ChainMap = typing.ChainMap
  778. __all__.append('ChainMap')
  779. elif hasattr(collections, 'ChainMap'):
  780. # ChainMap only exists in 3.3+
  781. if _geqv_defined:
  782. class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT],
  783. metaclass=_ExtensionsGenericMeta,
  784. extra=collections.ChainMap):
  785. __slots__ = ()
  786. def __new__(cls, *args, **kwds):
  787. if _geqv(cls, ChainMap):
  788. return collections.ChainMap(*args, **kwds)
  789. return _generic_new(collections.ChainMap, cls, *args, **kwds)
  790. else:
  791. class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT],
  792. metaclass=_ExtensionsGenericMeta,
  793. extra=collections.ChainMap):
  794. __slots__ = ()
  795. def __new__(cls, *args, **kwds):
  796. if cls._gorg is ChainMap:
  797. return collections.ChainMap(*args, **kwds)
  798. return _generic_new(collections.ChainMap, cls, *args, **kwds)
  799. __all__.append('ChainMap')
  800. if _define_guard('AsyncGenerator'):
  801. class AsyncGenerator(AsyncIterator[T_co], typing.Generic[T_co, T_contra],
  802. metaclass=_ExtensionsGenericMeta,
  803. extra=collections_abc.AsyncGenerator):
  804. __slots__ = ()
  805. if hasattr(typing, 'NewType'):
  806. NewType = typing.NewType
  807. else:
  808. def NewType(name, tp):
  809. """NewType creates simple unique types with almost zero
  810. runtime overhead. NewType(name, tp) is considered a subtype of tp
  811. by static type checkers. At runtime, NewType(name, tp) returns
  812. a dummy function that simply returns its argument. Usage::
  813. UserId = NewType('UserId', int)
  814. def name_by_id(user_id: UserId) -> str:
  815. ...
  816. UserId('user') # Fails type check
  817. name_by_id(42) # Fails type check
  818. name_by_id(UserId(42)) # OK
  819. num = UserId(5) + 1 # type: int
  820. """
  821. def new_type(x):
  822. return x
  823. new_type.__name__ = name
  824. new_type.__supertype__ = tp
  825. return new_type
  826. if hasattr(typing, 'Text'):
  827. Text = typing.Text
  828. else:
  829. Text = str
  830. if hasattr(typing, 'TYPE_CHECKING'):
  831. TYPE_CHECKING = typing.TYPE_CHECKING
  832. else:
  833. # Constant that's True when type checking, but False here.
  834. TYPE_CHECKING = False
  835. def _gorg(cls):
  836. """This function exists for compatibility with old typing versions."""
  837. assert isinstance(cls, GenericMeta)
  838. if hasattr(cls, '_gorg'):
  839. return cls._gorg
  840. while cls.__origin__ is not None:
  841. cls = cls.__origin__
  842. return cls
  843. if OLD_GENERICS:
  844. def _next_in_mro(cls):
  845. """This function exists for compatibility with old typing versions."""
  846. next_in_mro = object
  847. for i, c in enumerate(cls.__mro__[:-1]):
  848. if isinstance(c, GenericMeta) and _gorg(c) is Generic:
  849. next_in_mro = cls.__mro__[i + 1]
  850. return next_in_mro
  851. _PROTO_WHITELIST = ['Callable', 'Awaitable',
  852. 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
  853. 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
  854. 'ContextManager', 'AsyncContextManager']
  855. def _get_protocol_attrs(cls):
  856. attrs = set()
  857. for base in cls.__mro__[:-1]: # without object
  858. if base.__name__ in ('Protocol', 'Generic'):
  859. continue
  860. annotations = getattr(base, '__annotations__', {})
  861. for attr in list(base.__dict__.keys()) + list(annotations.keys()):
  862. if (not attr.startswith('_abc_') and attr not in (
  863. '__abstractmethods__', '__annotations__', '__weakref__',
  864. '_is_protocol', '_is_runtime_protocol', '__dict__',
  865. '__args__', '__slots__',
  866. '__next_in_mro__', '__parameters__', '__origin__',
  867. '__orig_bases__', '__extra__', '__tree_hash__',
  868. '__doc__', '__subclasshook__', '__init__', '__new__',
  869. '__module__', '_MutableMapping__marker', '_gorg')):
  870. attrs.add(attr)
  871. return attrs
  872. def _is_callable_members_only(cls):
  873. return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
  874. if hasattr(typing, 'Protocol'):
  875. Protocol = typing.Protocol
  876. elif HAVE_PROTOCOLS and not PEP_560:
  877. class _ProtocolMeta(GenericMeta):
  878. """Internal metaclass for Protocol.
  879. This exists so Protocol classes can be generic without deriving
  880. from Generic.
  881. """
  882. if not OLD_GENERICS:
  883. def __new__(cls, name, bases, namespace,
  884. tvars=None, args=None, origin=None, extra=None, orig_bases=None):
  885. # This is just a version copied from GenericMeta.__new__ that
  886. # includes "Protocol" special treatment. (Comments removed for brevity.)
  887. assert extra is None # Protocols should not have extra
  888. if tvars is not None:
  889. assert origin is not None
  890. assert all(isinstance(t, TypeVar) for t in tvars), tvars
  891. else:
  892. tvars = _type_vars(bases)
  893. gvars = None
  894. for base in bases:
  895. if base is Generic:
  896. raise TypeError("Cannot inherit from plain Generic")
  897. if (isinstance(base, GenericMeta) and
  898. base.__origin__ in (Generic, Protocol)):
  899. if gvars is not None:
  900. raise TypeError(
  901. "Cannot inherit from Generic[...] or"
  902. " Protocol[...] multiple times.")
  903. gvars = base.__parameters__
  904. if gvars is None:
  905. gvars = tvars
  906. else:
  907. tvarset = set(tvars)
  908. gvarset = set(gvars)
  909. if not tvarset <= gvarset:
  910. raise TypeError(
  911. "Some type variables (%s) "
  912. "are not listed in %s[%s]" %
  913. (", ".join(str(t) for t in tvars if t not in gvarset),
  914. "Generic" if any(b.__origin__ is Generic
  915. for b in bases) else "Protocol",
  916. ", ".join(str(g) for g in gvars)))
  917. tvars = gvars
  918. initial_bases = bases
  919. if (extra is not None and type(extra) is abc.ABCMeta and
  920. extra not in bases):
  921. bases = (extra,) + bases
  922. bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b
  923. for b in bases)
  924. if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
  925. bases = tuple(b for b in bases if b is not Generic)
  926. namespace.update({'__origin__': origin, '__extra__': extra})
  927. self = super(GenericMeta, cls).__new__(cls, name, bases, namespace,
  928. _root=True)
  929. super(GenericMeta, self).__setattr__('_gorg',
  930. self if not origin else
  931. _gorg(origin))
  932. self.__parameters__ = tvars
  933. self.__args__ = tuple(... if a is _TypingEllipsis else
  934. () if a is _TypingEmpty else
  935. a for a in args) if args else None
  936. self.__next_in_mro__ = _next_in_mro(self)
  937. if orig_bases is None:
  938. self.__orig_bases__ = initial_bases
  939. elif origin is not None:
  940. self._abc_registry = origin._abc_registry
  941. self._abc_cache = origin._abc_cache
  942. if hasattr(self, '_subs_tree'):
  943. self.__tree_hash__ = (hash(self._subs_tree()) if origin else
  944. super(GenericMeta, self).__hash__())
  945. return self
  946. def __init__(cls, *args, **kwargs):
  947. super().__init__(*args, **kwargs)
  948. if not cls.__dict__.get('_is_protocol', None):
  949. cls._is_protocol = any(b is Protocol or
  950. isinstance(b, _ProtocolMeta) and
  951. b.__origin__ is Protocol
  952. for b in cls.__bases__)
  953. if cls._is_protocol:
  954. for base in cls.__mro__[1:]:
  955. if not (base in (object, Generic) or
  956. base.__module__ == 'collections.abc' and
  957. base.__name__ in _PROTO_WHITELIST or
  958. isinstance(base, TypingMeta) and base._is_protocol or
  959. isinstance(base, GenericMeta) and
  960. base.__origin__ is Generic):
  961. raise TypeError('Protocols can only inherit from other'
  962. ' protocols, got %r' % base)
  963. def _no_init(self, *args, **kwargs):
  964. if type(self)._is_protocol:
  965. raise TypeError('Protocols cannot be instantiated')
  966. cls.__init__ = _no_init
  967. def _proto_hook(other):
  968. if not cls.__dict__.get('_is_protocol', None):
  969. return NotImplemented
  970. if not isinstance(other, type):
  971. # Same error as for issubclass(1, int)
  972. raise TypeError('issubclass() arg 1 must be a class')
  973. for attr in _get_protocol_attrs(cls):
  974. for base in other.__mro__:
  975. if attr in base.__dict__:
  976. if base.__dict__[attr] is None:
  977. return NotImplemented
  978. break
  979. annotations = getattr(base, '__annotations__', {})
  980. if (isinstance(annotations, typing.Mapping) and attr in annotations and
  981. isinstance(other, _ProtocolMeta) and other._is_protocol):
  982. break
  983. else:
  984. return NotImplemented
  985. return True
  986. if '__subclasshook__' not in cls.__dict__:
  987. cls.__subclasshook__ = _proto_hook
  988. def __instancecheck__(self, instance):
  989. # We need this method for situations where attributes are
  990. # assigned in __init__.
  991. if ((not getattr(self, '_is_protocol', False) or
  992. _is_callable_members_only(self)) and
  993. issubclass(instance.__class__, self)):
  994. return True
  995. if self._is_protocol:
  996. if all(hasattr(instance, attr) and
  997. (not callable(getattr(self, attr, None)) or
  998. getattr(instance, attr) is not None)
  999. for attr in _get_protocol_attrs(self)):
  1000. return True
  1001. return super(GenericMeta, self).__instancecheck__(instance)
  1002. def __subclasscheck__(self, cls):
  1003. if self.__origin__ is not None:
  1004. if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
  1005. raise TypeError("Parameterized generics cannot be used with class "
  1006. "or instance checks")
  1007. return False
  1008. if (self.__dict__.get('_is_protocol', None) and
  1009. not self.__dict__.get('_is_runtime_protocol', None)):
  1010. if sys._getframe(1).f_globals['__name__'] in ['abc', 'functools', 'typing']:
  1011. return False
  1012. raise TypeError("Instance and class checks can only be used with"
  1013. " @runtime protocols")
  1014. if (self.__dict__.get('_is_runtime_protocol', None) and
  1015. not _is_callable_members_only(self)):
  1016. if sys._getframe(1).f_globals['__name__'] in ['abc', 'functools', 'typing']:
  1017. return super(GenericMeta, self).__subclasscheck__(cls)
  1018. raise TypeError("Protocols with non-method members"
  1019. " don't support issubclass()")
  1020. return super(GenericMeta, self).__subclasscheck__(cls)
  1021. if not OLD_GENERICS:
  1022. @_tp_cache
  1023. def __getitem__(self, params):
  1024. # We also need to copy this from GenericMeta.__getitem__ to get
  1025. # special treatment of "Protocol". (Comments removed for brevity.)
  1026. if not isinstance(params, tuple):
  1027. params = (params,)
  1028. if not params and _gorg(self) is not Tuple:
  1029. raise TypeError(
  1030. "Parameter list to %s[...] cannot be empty" % self.__qualname__)
  1031. msg = "Parameters to generic types must be types."
  1032. params = tuple(_type_check(p, msg) for p in params)
  1033. if self in (Generic, Protocol):
  1034. if not all(isinstance(p, TypeVar) for p in params):
  1035. raise TypeError(
  1036. "Parameters to %r[...] must all be type variables" % self)
  1037. if len(set(params)) != len(params):
  1038. raise TypeError(
  1039. "Parameters to %r[...] must all be unique" % self)
  1040. tvars = params
  1041. args = params
  1042. elif self in (Tuple, Callable):
  1043. tvars = _type_vars(params)
  1044. args = params
  1045. elif self.__origin__ in (Generic, Protocol):
  1046. raise TypeError("Cannot subscript already-subscripted %s" %
  1047. repr(self))
  1048. else:
  1049. _check_generic(self, params)
  1050. tvars = _type_vars(params)
  1051. args = params
  1052. prepend = (self,) if self.__origin__ is None else ()
  1053. return self.__class__(self.__name__,
  1054. prepend + self.__bases__,
  1055. _no_slots_copy(self.__dict__),
  1056. tvars=tvars,
  1057. args=args,
  1058. origin=self,
  1059. extra=self.__extra__,
  1060. orig_bases=self.__orig_bases__)
  1061. class Protocol(metaclass=_ProtocolMeta):
  1062. """Base class for protocol classes. Protocol classes are defined as::
  1063. class Proto(Protocol):
  1064. def meth(self) -> int:
  1065. ...
  1066. Such classes are primarily used with static type checkers that recognize
  1067. structural subtyping (static duck-typing), for example::
  1068. class C:
  1069. def meth(self) -> int:
  1070. return 0
  1071. def func(x: Proto) -> int:
  1072. return x.meth()
  1073. func(C()) # Passes static type check
  1074. See PEP 544 for details. Protocol classes decorated with
  1075. @typing_extensions.runtime act as simple-minded runtime protocol that checks
  1076. only the presence of given attributes, ignoring their type signatures.
  1077. Protocol classes can be generic, they are defined as::
  1078. class GenProto({bases}):
  1079. def meth(self) -> T:
  1080. ...
  1081. """
  1082. __slots__ = ()
  1083. _is_protocol = True
  1084. def __new__(cls, *args, **kwds):
  1085. if _gorg(cls) is Protocol:
  1086. raise TypeError("Type Protocol cannot be instantiated; "
  1087. "it can be used only as a base class")
  1088. if OLD_GENERICS:
  1089. return _generic_new(_next_in_mro(cls), cls, *args, **kwds)
  1090. return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
  1091. if Protocol.__doc__ is not None:
  1092. Protocol.__doc__ = Protocol.__doc__.format(bases="Protocol, Generic[T]" if
  1093. OLD_GENERICS else "Protocol[T]")
  1094. elif PEP_560:
  1095. from typing import _type_check, _GenericAlias, _collect_type_vars
  1096. class _ProtocolMeta(abc.ABCMeta):
  1097. # This metaclass is a bit unfortunate and exists only because of the lack
  1098. # of __instancehook__.
  1099. def __instancecheck__(cls, instance):
  1100. # We need this method for situations where attributes are
  1101. # assigned in __init__.
  1102. if ((not getattr(cls, '_is_protocol', False) or
  1103. _is_callable_members_only(cls)) and
  1104. issubclass(instance.__class__, cls)):
  1105. return True
  1106. if cls._is_protocol:
  1107. if all(hasattr(instance, attr) and
  1108. (not callable(getattr(cls, attr, None)) or
  1109. getattr(instance, attr) is not None)
  1110. for attr in _get_protocol_attrs(cls)):
  1111. return True
  1112. return super().__instancecheck__(instance)
  1113. class Protocol(metaclass=_ProtocolMeta):
  1114. # There is quite a lot of overlapping code with typing.Generic.
  1115. # Unfortunately it is hard to avoid this while these live in two different modules.
  1116. # The duplicated code will be removed when Protocol is moved to typing.
  1117. """Base class for protocol classes. Protocol classes are defined as::
  1118. class Proto(Protocol):
  1119. def meth(self) -> int:
  1120. ...
  1121. Such classes are primarily used with static type checkers that recognize
  1122. structural subtyping (static duck-typing), for example::
  1123. class C:
  1124. def meth(self) -> int:
  1125. return 0
  1126. def func(x: Proto) -> int:
  1127. return x.meth()
  1128. func(C()) # Passes static type check
  1129. See PEP 544 for details. Protocol classes decorated with
  1130. @typing_extensions.runtime act as simple-minded runtime protocol that checks
  1131. only the presence of given attributes, ignoring their type signatures.
  1132. Protocol classes can be generic, they are defined as::
  1133. class GenProto(Protocol[T]):
  1134. def meth(self) -> T:
  1135. ...
  1136. """
  1137. __slots__ = ()
  1138. _is_protocol = True
  1139. def __new__(cls, *args, **kwds):
  1140. if cls is Protocol:
  1141. raise TypeError("Type Protocol cannot be instantiated; "
  1142. "it can only be used as a base class")
  1143. return super().__new__(cls)
  1144. @_tp_cache
  1145. def __class_getitem__(cls, params):
  1146. if not isinstance(params, tuple):
  1147. params = (params,)
  1148. if not params and cls is not Tuple:
  1149. raise TypeError(
  1150. "Parameter list to {}[...] cannot be empty".format(cls.__qualname__))
  1151. msg = "Parameters to generic types must be types."
  1152. params = tuple(_type_check(p, msg) for p in params)
  1153. if cls is Protocol:
  1154. # Generic can only be subscripted with unique type variables.
  1155. if not all(isinstance(p, TypeVar) for p in params):
  1156. i = 0
  1157. while isinstance(params[i], TypeVar):
  1158. i += 1
  1159. raise TypeError(
  1160. "Parameters to Protocol[...] must all be type variables."
  1161. " Parameter {} is {}".format(i + 1, params[i]))
  1162. if len(set(params)) != len(params):
  1163. raise TypeError(
  1164. "Parameters to Protocol[...] must all be unique")
  1165. else:
  1166. # Subscripting a regular Generic subclass.
  1167. _check_generic(cls, params)
  1168. return _GenericAlias(cls, params)
  1169. def __init_subclass__(cls, *args, **kwargs):
  1170. tvars = []
  1171. if '__orig_bases__' in cls.__dict__:
  1172. error = Generic in cls.__orig_bases__
  1173. else:
  1174. error = Generic in cls.__bases__
  1175. if error:
  1176. raise TypeError("Cannot inherit from plain Generic")
  1177. if '__orig_bases__' in cls.__dict__:
  1178. tvars = _collect_type_vars(cls.__orig_bases__)
  1179. # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
  1180. # If found, tvars must be a subset of it.
  1181. # If not found, tvars is it.
  1182. # Also check for and reject plain Generic,
  1183. # and reject multiple Generic[...] and/or Protocol[...].
  1184. gvars = None
  1185. for base in cls.__orig_bases__:
  1186. if (isinstance(base, _GenericAlias) and
  1187. base.__origin__ in (Generic, Protocol)):
  1188. # for error messages
  1189. the_base = 'Generic' if base.__origin__ is Generic else 'Protocol'
  1190. if gvars is not None:
  1191. raise TypeError(
  1192. "Cannot inherit from Generic[...]"
  1193. " and/or Protocol[...] multiple types.")
  1194. gvars = base.__parameters__
  1195. if gvars is None:
  1196. gvars = tvars
  1197. else:
  1198. tvarset = set(tvars)
  1199. gvarset = set(gvars)
  1200. if not tvarset <= gvarset:
  1201. s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
  1202. s_args = ', '.join(str(g) for g in gvars)
  1203. raise TypeError("Some type variables ({}) are"
  1204. " not listed in {}[{}]".format(s_vars, the_base, s_args))
  1205. tvars = gvars
  1206. cls.__parameters__ = tuple(tvars)
  1207. # Determine if this is a protocol or a concrete subclass.
  1208. if not cls.__dict__.get('_is_protocol', None):
  1209. cls._is_protocol = any(b is Protocol for b in cls.__bases__)
  1210. # Set (or override) the protocol subclass hook.
  1211. def _proto_hook(other):
  1212. if not cls.__dict__.get('_is_protocol', None):
  1213. return NotImplemented
  1214. if not getattr(cls, '_is_runtime_protocol', False):
  1215. if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
  1216. return NotImplemented
  1217. raise TypeError("Instance and class checks can only be used with"
  1218. " @runtime protocols")
  1219. if not _is_callable_members_only(cls):
  1220. if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
  1221. return NotImplemented
  1222. raise TypeError("Protocols with non-method members"
  1223. " don't support issubclass()")
  1224. if not isinstance(other, type):
  1225. # Same error as for issubclass(1, int)
  1226. raise TypeError('issubclass() arg 1 must be a class')
  1227. for attr in _get_protocol_attrs(cls):
  1228. for base in other.__mro__:
  1229. if attr in base.__dict__:
  1230. if base.__dict__[attr] is None:
  1231. return NotImplemented
  1232. break
  1233. annotations = getattr(base, '__annotations__', {})
  1234. if (isinstance(annotations, typing.Mapping) and attr in annotations and
  1235. isinstance(other, _ProtocolMeta) and other._is_protocol):
  1236. break
  1237. else:
  1238. return NotImplemented
  1239. return True
  1240. if '__subclasshook__' not in cls.__dict__:
  1241. cls.__subclasshook__ = _proto_hook
  1242. # We have nothing more to do for non-protocols.
  1243. if not cls._is_protocol:
  1244. return
  1245. # Check consistency of bases.
  1246. for base in cls.__bases__:
  1247. if not (base in (object, Generic) or
  1248. base.__module__ == 'collections.abc' and
  1249. base.__name__ in _PROTO_WHITELIST or
  1250. isinstance(base, _ProtocolMeta) and base._is_protocol):
  1251. raise TypeError('Protocols can only inherit from other'
  1252. ' protocols, got %r' % base)
  1253. def _no_init(self, *args, **kwargs):
  1254. if type(self)._is_protocol:
  1255. raise TypeError('Protocols cannot be instantiated')
  1256. cls.__init__ = _no_init
  1257. if hasattr(typing, 'runtime_checkable'):
  1258. runtime_checkable = typing.runtime_checkable
  1259. elif HAVE_PROTOCOLS:
  1260. def runtime_checkable(cls):
  1261. """Mark a protocol class as a runtime protocol, so that it
  1262. can be used with isinstance() and issubclass(). Raise TypeError
  1263. if applied to a non-protocol class.
  1264. This allows a simple-minded structural check very similar to the
  1265. one-offs in collections.abc such as Hashable.
  1266. """
  1267. if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
  1268. raise TypeError('@runtime_checkable can be only applied to protocol classes,'
  1269. ' got %r' % cls)
  1270. cls._is_runtime_protocol = True
  1271. return cls
  1272. if HAVE_PROTOCOLS:
  1273. # Exists for backwards compatibility.
  1274. runtime = runtime_checkable
  1275. if hasattr(typing, 'TypedDict'):
  1276. TypedDict = typing.TypedDict
  1277. else:
  1278. def _check_fails(cls, other):
  1279. try:
  1280. if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools', 'typing']:
  1281. # Typed dicts are only for static structural subtyping.
  1282. raise TypeError('TypedDict does not support instance and class checks')
  1283. except (AttributeError, ValueError):
  1284. pass
  1285. return False
  1286. def _dict_new(cls, *args, **kwargs):
  1287. return dict(*args, **kwargs)
  1288. def _typeddict_new(cls, _typename, _fields=None, **kwargs):
  1289. total = kwargs.pop('total', True)
  1290. if _fields is None:
  1291. _fields = kwargs
  1292. elif kwargs:
  1293. raise TypeError("TypedDict takes either a dict or keyword arguments,"
  1294. " but not both")
  1295. ns = {'__annotations__': dict(_fields), '__total__': total}
  1296. try:
  1297. # Setting correct module is necessary to make typed dict classes pickleable.
  1298. ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
  1299. except (AttributeError, ValueError):
  1300. pass
  1301. return _TypedDictMeta(_typename, (), ns)
  1302. class _TypedDictMeta(type):
  1303. def __new__(cls, name, bases, ns, total=True):
  1304. # Create new typed dict class object.
  1305. # This method is called directly when TypedDict is subclassed,
  1306. # or via _typeddict_new when TypedDict is instantiated. This way
  1307. # TypedDict supports all three syntaxes described in its docstring.
  1308. # Subclasses and instances of TypedDict return actual dictionaries
  1309. # via _dict_new.
  1310. ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
  1311. tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)
  1312. anns = ns.get('__annotations__', {})
  1313. msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
  1314. anns = {n: typing._type_check(tp, msg) for n, tp in anns.items()}
  1315. for base in bases:
  1316. anns.update(base.__dict__.get('__annotations__', {}))
  1317. tp_dict.__annotations__ = anns
  1318. if not hasattr(tp_dict, '__total__'):
  1319. tp_dict.__total__ = total
  1320. return tp_dict
  1321. __instancecheck__ = __subclasscheck__ = _check_fails
  1322. TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
  1323. TypedDict.__module__ = __name__
  1324. TypedDict.__doc__ = \
  1325. """A simple typed name space. At runtime it is equivalent to a plain dict.
  1326. TypedDict creates a dictionary type that expects all of its
  1327. instances to have a certain set of keys, with each key
  1328. associated with a value of a consistent type. This expectation
  1329. is not checked at runtime but is only enforced by type checkers.
  1330. Usage::
  1331. class Point2D(TypedDict):
  1332. x: int
  1333. y: int
  1334. label: str
  1335. a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
  1336. b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
  1337. assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
  1338. The type info could be accessed via Point2D.__annotations__. TypedDict
  1339. supports two additional equivalent forms::
  1340. Point2D = TypedDict('Point2D', x=int, y=int, label=str)
  1341. Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
  1342. The class syntax is only supported in Python 3.6+, while two other
  1343. syntax forms work for Python 2.7 and 3.2+
  1344. """
  1345. if PEP_560:
  1346. class _AnnotatedAlias(typing._GenericAlias, _root=True):
  1347. """Runtime representation of an annotated type.
  1348. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
  1349. with extra annotations. The alias behaves like a normal typing alias,
  1350. instantiating is the same as instantiating the underlying type, binding
  1351. it to types is also the same.
  1352. """
  1353. def __init__(self, origin, metadata):
  1354. if isinstance(origin, _AnnotatedAlias):
  1355. metadata = origin.__metadata__ + metadata
  1356. origin = origin.__origin__
  1357. super().__init__(origin, origin)
  1358. self.__metadata__ = metadata
  1359. def copy_with(self, params):
  1360. assert len(params) == 1
  1361. new_type = params[0]
  1362. return _AnnotatedAlias(new_type, self.__metadata__)
  1363. def __repr__(self):
  1364. return "typing_extensions.Annotated[{}, {}]".format(
  1365. typing._type_repr(self.__origin__),
  1366. ", ".join(repr(a) for a in self.__metadata__)
  1367. )
  1368. def __reduce__(self):
  1369. return operator.getitem, (
  1370. Annotated, (self.__origin__,) + self.__metadata__
  1371. )
  1372. def __eq__(self, other):
  1373. if not isinstance(other, _AnnotatedAlias):
  1374. return NotImplemented
  1375. if self.__origin__ != other.__origin__:
  1376. return False
  1377. return self.__metadata__ == other.__metadata__
  1378. def __hash__(self):
  1379. return hash((self.__origin__, self.__metadata__))
  1380. class Annotated:
  1381. """Add context specific metadata to a type.
  1382. Example: Annotated[int, runtime_check.Unsigned] indicates to the
  1383. hypothetical runtime_check module that this type is an unsigned int.
  1384. Every other consumer of this type can ignore this metadata and treat
  1385. this type as int.
  1386. The first argument to Annotated must be a valid type (and will be in
  1387. the __origin__ field), the remaining arguments are kept as a tuple in
  1388. the __extra__ field.
  1389. Details:
  1390. - It's an error to call `Annotated` with less than two arguments.
  1391. - Nested Annotated are flattened::
  1392. Annotated[Annotated[int, Ann1, Ann2], Ann3] == Annotated[int, Ann1, Ann2, Ann3]
  1393. - Instantiating an annotated type is equivalent to instantiating the
  1394. underlying type::
  1395. Annotated[C, Ann1](5) == C(5)
  1396. - Annotated can be used as a generic type alias::
  1397. Optimized = Annotated[T, runtime.Optimize()]
  1398. Optimized[int] == Annotated[int, runtime.Optimize()]
  1399. OptimizedList = Annotated[List[T], runtime.Optimize()]
  1400. OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
  1401. """
  1402. __slots__ = ()
  1403. def __new__(cls, *args, **kwargs):
  1404. raise TypeError("Type Annotated cannot be instantiated.")
  1405. @_tp_cache
  1406. def __class_getitem__(cls, params):
  1407. if not isinstance(params, tuple) or len(params) < 2:
  1408. raise TypeError("Annotated[...] should be used "
  1409. "with at least two arguments (a type and an "
  1410. "annotation).")
  1411. msg = "Annotated[t, ...]: t must be a type."
  1412. origin = typing._type_check(params[0], msg)
  1413. metadata = tuple(params[1:])
  1414. return _AnnotatedAlias(origin, metadata)
  1415. def __init_subclass__(cls, *args, **kwargs):
  1416. raise TypeError(
  1417. "Cannot subclass {}.Annotated".format(cls.__module__)
  1418. )
  1419. def _strip_annotations(t):
  1420. """Strips the annotations from a given type.
  1421. """
  1422. if isinstance(t, _AnnotatedAlias):
  1423. return _strip_annotations(t.__origin__)
  1424. if isinstance(t, typing._GenericAlias):
  1425. stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
  1426. if stripped_args == t.__args__:
  1427. return t
  1428. res = t.copy_with(stripped_args)
  1429. res._special = t._special
  1430. return res
  1431. return t
  1432. def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
  1433. """Return type hints for an object.
  1434. This is often the same as obj.__annotations__, but it handles
  1435. forward references encoded as string literals, adds Optional[t] if a
  1436. default value equal to None is set and recursively replaces all
  1437. 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
  1438. The argument may be a module, class, method, or function. The annotations
  1439. are returned as a dictionary. For classes, annotations include also
  1440. inherited members.
  1441. TypeError is raised if the argument is not of a type that can contain
  1442. annotations, and an empty dictionary is returned if no annotations are
  1443. present.
  1444. BEWARE -- the behavior of globalns and localns is counterintuitive
  1445. (unless you are familiar with how eval() and exec() work). The
  1446. search order is locals first, then globals.
  1447. - If no dict arguments are passed, an attempt is made to use the
  1448. globals from obj (or the respective module's globals for classes),
  1449. and these are also used as the locals. If the object does not appear
  1450. to have globals, an empty dictionary is used.
  1451. - If one dict argument is passed, it is used for both globals and
  1452. locals.
  1453. - If two dict arguments are passed, they specify globals and
  1454. locals, respectively.
  1455. """
  1456. hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
  1457. if include_extras:
  1458. return hint
  1459. return {k: _strip_annotations(t) for k, t in hint.items()}
  1460. elif HAVE_ANNOTATED:
  1461. def _is_dunder(name):
  1462. """Returns True if name is a __dunder_variable_name__."""
  1463. return len(name) > 4 and name.startswith('__') and name.endswith('__')
  1464. # Prior to Python 3.7 types did not have `copy_with`. A lot of the equality
  1465. # checks, argument expansion etc. are done on the _subs_tre. As a result we
  1466. # can't provide a get_type_hints function that strips out annotations.
  1467. class AnnotatedMeta(typing.GenericMeta):
  1468. """Metaclass for Annotated"""
  1469. def __new__(cls, name, bases, namespace, **kwargs):
  1470. if any(b is not object for b in bases):
  1471. raise TypeError("Cannot subclass " + str(Annotated))
  1472. return super().__new__(cls, name, bases, namespace, **kwargs)
  1473. @property
  1474. def __metadata__(self):
  1475. return self._subs_tree()[2]
  1476. def _tree_repr(self, tree):
  1477. cls, origin, metadata = tree
  1478. if not isinstance(origin, tuple):
  1479. tp_repr = typing._type_repr(origin)
  1480. else:
  1481. tp_repr = origin[0]._tree_repr(origin)
  1482. metadata_reprs = ", ".join(repr(arg) for arg in metadata)
  1483. return '%s[%s, %s]' % (cls, tp_repr, metadata_reprs)
  1484. def _subs_tree(self, tvars=None, args=None):
  1485. if self is Annotated:
  1486. return Annotated
  1487. res = super()._subs_tree(tvars=tvars, args=args)
  1488. # Flatten nested Annotated
  1489. if isinstance(res[1], tuple) and res[1][0] is Annotated:
  1490. sub_tp = res[1][1]
  1491. sub_annot = res[1][2]
  1492. return (Annotated, sub_tp, sub_annot + res[2])
  1493. return res
  1494. def _get_cons(self):
  1495. """Return the class used to create instance of this type."""
  1496. if self.__origin__ is None:
  1497. raise TypeError("Cannot get the underlying type of a "
  1498. "non-specialized Annotated type.")
  1499. tree = self._subs_tree()
  1500. while isinstance(tree, tuple) and tree[0] is Annotated:
  1501. tree = tree[1]
  1502. if isinstance(tree, tuple):
  1503. return tree[0]
  1504. else:
  1505. return tree
  1506. @_tp_cache
  1507. def __getitem__(self, params):
  1508. if not isinstance(params, tuple):
  1509. params = (params,)
  1510. if self.__origin__ is not None: # specializing an instantiated type
  1511. return super().__getitem__(params)
  1512. elif not isinstance(params, tuple) or len(params) < 2:
  1513. raise TypeError("Annotated[...] should be instantiated "
  1514. "with at least two arguments (a type and an "
  1515. "annotation).")
  1516. else:
  1517. msg = "Annotated[t, ...]: t must be a type."
  1518. tp = typing._type_check(params[0], msg)
  1519. metadata = tuple(params[1:])
  1520. return self.__class__(
  1521. self.__name__,
  1522. self.__bases__,
  1523. _no_slots_copy(self.__dict__),
  1524. tvars=_type_vars((tp,)),
  1525. # Metadata is a tuple so it won't be touched by _replace_args et al.
  1526. args=(tp, metadata),
  1527. origin=self,
  1528. )
  1529. def __call__(self, *args, **kwargs):
  1530. cons = self._get_cons()
  1531. result = cons(*args, **kwargs)
  1532. try:
  1533. result.__orig_class__ = self
  1534. except AttributeError:
  1535. pass
  1536. return result
  1537. def __getattr__(self, attr):
  1538. # For simplicity we just don't relay all dunder names
  1539. if self.__origin__ is not None and not _is_dunder(attr):
  1540. return getattr(self._get_cons(), attr)
  1541. raise AttributeError(attr)
  1542. def __setattr__(self, attr, value):
  1543. if _is_dunder(attr) or attr.startswith('_abc_'):
  1544. super().__setattr__(attr, value)
  1545. elif self.__origin__ is None:
  1546. raise AttributeError(attr)
  1547. else:
  1548. setattr(self._get_cons(), attr, value)
  1549. def __instancecheck__(self, obj):
  1550. raise TypeError("Annotated cannot be used with isinstance().")
  1551. def __subclasscheck__(self, cls):
  1552. raise TypeError("Annotated cannot be used with issubclass().")
  1553. class Annotated(metaclass=AnnotatedMeta):
  1554. """Add context specific metadata to a type.
  1555. Example: Annotated[int, runtime_check.Unsigned] indicates to the
  1556. hypothetical runtime_check module that this type is an unsigned int.
  1557. Every other consumer of this type can ignore this metadata and treat
  1558. this type as int.
  1559. The first argument to Annotated must be a valid type, the remaining
  1560. arguments are kept as a tuple in the __metadata__ field.
  1561. Details:
  1562. - It's an error to call `Annotated` with less than two arguments.
  1563. - Nested Annotated are flattened::
  1564. Annotated[Annotated[int, Ann1, Ann2], Ann3] == Annotated[int, Ann1, Ann2, Ann3]
  1565. - Instantiating an annotated type is equivalent to instantiating the
  1566. underlying type::
  1567. Annotated[C, Ann1](5) == C(5)
  1568. - Annotated can be used as a generic type alias::
  1569. Optimized = Annotated[T, runtime.Optimize()]
  1570. Optimized[int] == Annotated[int, runtime.Optimize()]
  1571. OptimizedList = Annotated[List[T], runtime.Optimize()]
  1572. OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
  1573. """