typing_extensions.py 106 KB

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