typing_extensions.py 107 KB

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