typing.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843
  1. import abc
  2. from abc import abstractmethod, abstractproperty
  3. import collections
  4. import contextlib
  5. import functools
  6. import re as stdlib_re # Avoid confusion with the re we export.
  7. import sys
  8. import types
  9. try:
  10. import collections.abc as collections_abc
  11. except ImportError:
  12. import collections as collections_abc # Fallback for PY3.2.
  13. # Please keep __all__ alphabetized within each category.
  14. __all__ = [
  15. # Super-special typing primitives.
  16. 'Any',
  17. 'Callable',
  18. 'Generic',
  19. 'Optional',
  20. 'Tuple',
  21. 'Type',
  22. 'TypeVar',
  23. 'Union',
  24. # ABCs (from collections.abc).
  25. 'AbstractSet', # collections.abc.Set.
  26. 'Awaitable',
  27. 'AsyncIterator',
  28. 'AsyncIterable',
  29. 'ByteString',
  30. 'Container',
  31. 'Hashable',
  32. 'ItemsView',
  33. 'Iterable',
  34. 'Iterator',
  35. 'KeysView',
  36. 'Mapping',
  37. 'MappingView',
  38. 'MutableMapping',
  39. 'MutableSequence',
  40. 'MutableSet',
  41. 'Sequence',
  42. 'Sized',
  43. 'ValuesView',
  44. # Structural checks, a.k.a. protocols.
  45. 'Reversible',
  46. 'SupportsAbs',
  47. 'SupportsFloat',
  48. 'SupportsInt',
  49. 'SupportsRound',
  50. # Concrete collection types.
  51. 'Dict',
  52. 'DefaultDict',
  53. 'List',
  54. 'Set',
  55. 'NamedTuple', # Not really a type.
  56. 'Generator',
  57. # One-off things.
  58. 'AnyStr',
  59. 'cast',
  60. 'get_type_hints',
  61. 'NewType',
  62. 'no_type_check',
  63. 'no_type_check_decorator',
  64. 'overload',
  65. 'Text',
  66. 'TYPE_CHECKING',
  67. ]
  68. # The pseudo-submodules 're' and 'io' are part of the public
  69. # namespace, but excluded from __all__ because they might stomp on
  70. # legitimate imports of those modules.
  71. def _qualname(x):
  72. if sys.version_info[:2] >= (3, 3):
  73. return x.__qualname__
  74. else:
  75. # Fall back to just name.
  76. return x.__name__
  77. class TypingMeta(type):
  78. """Metaclass for every type defined below.
  79. This overrides __new__() to require an extra keyword parameter
  80. '_root', which serves as a guard against naive subclassing of the
  81. typing classes. Any legitimate class defined using a metaclass
  82. derived from TypingMeta (including internal subclasses created by
  83. e.g. Union[X, Y]) must pass _root=True.
  84. This also defines a dummy constructor (all the work is done in
  85. __new__) and a nicer repr().
  86. """
  87. _is_protocol = False
  88. def __new__(cls, name, bases, namespace, *, _root=False):
  89. if not _root:
  90. raise TypeError("Cannot subclass %s" %
  91. (', '.join(map(_type_repr, bases)) or '()'))
  92. return super().__new__(cls, name, bases, namespace)
  93. def __init__(self, *args, **kwds):
  94. pass
  95. def _eval_type(self, globalns, localns):
  96. """Override this in subclasses to interpret forward references.
  97. For example, Union['C'] is internally stored as
  98. Union[_ForwardRef('C')], which should evaluate to _Union[C],
  99. where C is an object found in globalns or localns (searching
  100. localns first, of course).
  101. """
  102. return self
  103. def _get_type_vars(self, tvars):
  104. pass
  105. def __repr__(self):
  106. return '%s.%s' % (self.__module__, _qualname(self))
  107. class Final:
  108. """Mix-in class to prevent instantiation."""
  109. __slots__ = ()
  110. def __new__(self, *args, **kwds):
  111. raise TypeError("Cannot instantiate %r" % self.__class__)
  112. class _ForwardRef(TypingMeta):
  113. """Wrapper to hold a forward reference."""
  114. def __new__(cls, arg):
  115. if not isinstance(arg, str):
  116. raise TypeError('ForwardRef must be a string -- got %r' % (arg,))
  117. try:
  118. code = compile(arg, '<string>', 'eval')
  119. except SyntaxError:
  120. raise SyntaxError('ForwardRef must be an expression -- got %r' %
  121. (arg,))
  122. self = super().__new__(cls, arg, (), {}, _root=True)
  123. self.__forward_arg__ = arg
  124. self.__forward_code__ = code
  125. self.__forward_evaluated__ = False
  126. self.__forward_value__ = None
  127. typing_globals = globals()
  128. frame = sys._getframe(1)
  129. while frame is not None and frame.f_globals is typing_globals:
  130. frame = frame.f_back
  131. assert frame is not None
  132. self.__forward_frame__ = frame
  133. return self
  134. def _eval_type(self, globalns, localns):
  135. if not isinstance(localns, dict):
  136. raise TypeError('ForwardRef localns must be a dict -- got %r' %
  137. (localns,))
  138. if not isinstance(globalns, dict):
  139. raise TypeError('ForwardRef globalns must be a dict -- got %r' %
  140. (globalns,))
  141. if not self.__forward_evaluated__:
  142. if globalns is None and localns is None:
  143. globalns = localns = {}
  144. elif globalns is None:
  145. globalns = localns
  146. elif localns is None:
  147. localns = globalns
  148. self.__forward_value__ = _type_check(
  149. eval(self.__forward_code__, globalns, localns),
  150. "Forward references must evaluate to types.")
  151. self.__forward_evaluated__ = True
  152. return self.__forward_value__
  153. def __instancecheck__(self, obj):
  154. raise TypeError("Forward references cannot be used with isinstance().")
  155. def __subclasscheck__(self, cls):
  156. if not self.__forward_evaluated__:
  157. globalns = self.__forward_frame__.f_globals
  158. localns = self.__forward_frame__.f_locals
  159. try:
  160. self._eval_type(globalns, localns)
  161. except NameError:
  162. return False # Too early.
  163. return issubclass(cls, self.__forward_value__)
  164. def __repr__(self):
  165. return '_ForwardRef(%r)' % (self.__forward_arg__,)
  166. class _TypeAlias:
  167. """Internal helper class for defining generic variants of concrete types.
  168. Note that this is not a type; let's call it a pseudo-type. It can
  169. be used in instance and subclass checks, e.g. isinstance(m, Match)
  170. or issubclass(type(m), Match). However, it cannot be itself the
  171. target of an issubclass() call; e.g. issubclass(Match, C) (for
  172. some arbitrary class C) raises TypeError rather than returning
  173. False.
  174. """
  175. __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
  176. def __new__(cls, *args, **kwds):
  177. """Constructor.
  178. This only exists to give a better error message in case
  179. someone tries to subclass a type alias (not a good idea).
  180. """
  181. if (len(args) == 3 and
  182. isinstance(args[0], str) and
  183. isinstance(args[1], tuple)):
  184. # Close enough.
  185. raise TypeError("A type alias cannot be subclassed")
  186. return object.__new__(cls)
  187. def __init__(self, name, type_var, impl_type, type_checker):
  188. """Initializer.
  189. Args:
  190. name: The name, e.g. 'Pattern'.
  191. type_var: The type parameter, e.g. AnyStr, or the
  192. specific type, e.g. str.
  193. impl_type: The implementation type.
  194. type_checker: Function that takes an impl_type instance.
  195. and returns a value that should be a type_var instance.
  196. """
  197. assert isinstance(name, str), repr(name)
  198. assert isinstance(type_var, type), repr(type_var)
  199. assert isinstance(impl_type, type), repr(impl_type)
  200. assert not isinstance(impl_type, TypingMeta), repr(impl_type)
  201. self.name = name
  202. self.type_var = type_var
  203. self.impl_type = impl_type
  204. self.type_checker = type_checker
  205. def __repr__(self):
  206. return "%s[%s]" % (self.name, _type_repr(self.type_var))
  207. def __getitem__(self, parameter):
  208. assert isinstance(parameter, type), repr(parameter)
  209. if not isinstance(self.type_var, TypeVar):
  210. raise TypeError("%s cannot be further parameterized." % self)
  211. if self.type_var.__constraints__:
  212. if not issubclass(parameter, Union[self.type_var.__constraints__]):
  213. raise TypeError("%s is not a valid substitution for %s." %
  214. (parameter, self.type_var))
  215. return self.__class__(self.name, parameter,
  216. self.impl_type, self.type_checker)
  217. def __instancecheck__(self, obj):
  218. raise TypeError("Type aliases cannot be used with isinstance().")
  219. def __subclasscheck__(self, cls):
  220. if cls is Any:
  221. return True
  222. if isinstance(cls, _TypeAlias):
  223. # Covariance. For now, we compare by name.
  224. return (cls.name == self.name and
  225. issubclass(cls.type_var, self.type_var))
  226. else:
  227. # Note that this is too lenient, because the
  228. # implementation type doesn't carry information about
  229. # whether it is about bytes or str (for example).
  230. return issubclass(cls, self.impl_type)
  231. def _get_type_vars(types, tvars):
  232. for t in types:
  233. if isinstance(t, TypingMeta):
  234. t._get_type_vars(tvars)
  235. def _type_vars(types):
  236. tvars = []
  237. _get_type_vars(types, tvars)
  238. return tuple(tvars)
  239. def _eval_type(t, globalns, localns):
  240. if isinstance(t, TypingMeta):
  241. return t._eval_type(globalns, localns)
  242. else:
  243. return t
  244. def _type_check(arg, msg):
  245. """Check that the argument is a type, and return it.
  246. As a special case, accept None and return type(None) instead.
  247. Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
  248. The msg argument is a human-readable error message, e.g.
  249. "Union[arg, ...]: arg should be a type."
  250. We append the repr() of the actual value (truncated to 100 chars).
  251. """
  252. if arg is None:
  253. return type(None)
  254. if isinstance(arg, str):
  255. arg = _ForwardRef(arg)
  256. if not isinstance(arg, (type, _TypeAlias)) and not callable(arg):
  257. raise TypeError(msg + " Got %.100r." % (arg,))
  258. return arg
  259. def _type_repr(obj):
  260. """Return the repr() of an object, special-casing types.
  261. If obj is a type, we return a shorter version than the default
  262. type.__repr__, based on the module and qualified name, which is
  263. typically enough to uniquely identify a type. For everything
  264. else, we fall back on repr(obj).
  265. """
  266. if isinstance(obj, type) and not isinstance(obj, TypingMeta):
  267. if obj.__module__ == 'builtins':
  268. return _qualname(obj)
  269. else:
  270. return '%s.%s' % (obj.__module__, _qualname(obj))
  271. else:
  272. return repr(obj)
  273. class AnyMeta(TypingMeta):
  274. """Metaclass for Any."""
  275. def __new__(cls, name, bases, namespace, _root=False):
  276. self = super().__new__(cls, name, bases, namespace, _root=_root)
  277. return self
  278. def __instancecheck__(self, obj):
  279. raise TypeError("Any cannot be used with isinstance().")
  280. def __subclasscheck__(self, cls):
  281. if not isinstance(cls, type):
  282. return super().__subclasscheck__(cls) # To TypeError.
  283. return True
  284. class Any(Final, metaclass=AnyMeta, _root=True):
  285. """Special type indicating an unconstrained type.
  286. - Any object is an instance of Any.
  287. - Any class is a subclass of Any.
  288. - As a special case, Any and object are subclasses of each other.
  289. """
  290. __slots__ = ()
  291. class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
  292. """Type variable.
  293. Usage::
  294. T = TypeVar('T') # Can be anything
  295. A = TypeVar('A', str, bytes) # Must be str or bytes
  296. Type variables exist primarily for the benefit of static type
  297. checkers. They serve as the parameters for generic types as well
  298. as for generic function definitions. See class Generic for more
  299. information on generic types. Generic functions work as follows:
  300. def repeat(x: T, n: int) -> Sequence[T]:
  301. '''Return a list containing n references to x.'''
  302. return [x]*n
  303. def longest(x: A, y: A) -> A:
  304. '''Return the longest of two strings.'''
  305. return x if len(x) >= len(y) else y
  306. The latter example's signature is essentially the overloading
  307. of (str, str) -> str and (bytes, bytes) -> bytes. Also note
  308. that if the arguments are instances of some subclass of str,
  309. the return type is still plain str.
  310. At runtime, isinstance(x, T) will raise TypeError. However,
  311. issubclass(C, T) is true for any class C, and issubclass(str, A)
  312. and issubclass(bytes, A) are true, and issubclass(int, A) is
  313. false. (TODO: Why is this needed? This may change. See #136.)
  314. Type variables may be marked covariant or contravariant by passing
  315. covariant=True or contravariant=True. See PEP 484 for more
  316. details. By default type variables are invariant.
  317. Type variables can be introspected. e.g.:
  318. T.__name__ == 'T'
  319. T.__constraints__ == ()
  320. T.__covariant__ == False
  321. T.__contravariant__ = False
  322. A.__constraints__ == (str, bytes)
  323. """
  324. def __new__(cls, name, *constraints, bound=None,
  325. covariant=False, contravariant=False):
  326. self = super().__new__(cls, name, (Final,), {}, _root=True)
  327. if covariant and contravariant:
  328. raise ValueError("Bivariant type variables are not supported.")
  329. self.__covariant__ = bool(covariant)
  330. self.__contravariant__ = bool(contravariant)
  331. if constraints and bound is not None:
  332. raise TypeError("Constraints cannot be combined with bound=...")
  333. if constraints and len(constraints) == 1:
  334. raise TypeError("A single constraint is not allowed")
  335. msg = "TypeVar(name, constraint, ...): constraints must be types."
  336. self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
  337. if bound:
  338. self.__bound__ = _type_check(bound, "Bound must be a type.")
  339. else:
  340. self.__bound__ = None
  341. return self
  342. def _get_type_vars(self, tvars):
  343. if self not in tvars:
  344. tvars.append(self)
  345. def __repr__(self):
  346. if self.__covariant__:
  347. prefix = '+'
  348. elif self.__contravariant__:
  349. prefix = '-'
  350. else:
  351. prefix = '~'
  352. return prefix + self.__name__
  353. def __instancecheck__(self, instance):
  354. raise TypeError("Type variables cannot be used with isinstance().")
  355. def __subclasscheck__(self, cls):
  356. # TODO: Make this raise TypeError too?
  357. if cls is self:
  358. return True
  359. if cls is Any:
  360. return True
  361. if self.__bound__ is not None:
  362. return issubclass(cls, self.__bound__)
  363. if self.__constraints__:
  364. return any(issubclass(cls, c) for c in self.__constraints__)
  365. return True
  366. # Some unconstrained type variables. These are used by the container types.
  367. # (These are not for export.)
  368. T = TypeVar('T') # Any type.
  369. KT = TypeVar('KT') # Key type.
  370. VT = TypeVar('VT') # Value type.
  371. T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
  372. V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
  373. VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
  374. T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
  375. # A useful type variable with constraints. This represents string types.
  376. # (This one *is* for export!)
  377. AnyStr = TypeVar('AnyStr', bytes, str)
  378. class UnionMeta(TypingMeta):
  379. """Metaclass for Union."""
  380. def __new__(cls, name, bases, namespace, parameters=None, _root=False):
  381. if parameters is None:
  382. return super().__new__(cls, name, bases, namespace, _root=_root)
  383. if not isinstance(parameters, tuple):
  384. raise TypeError("Expected parameters=<tuple>")
  385. # Flatten out Union[Union[...], ...] and type-check non-Union args.
  386. params = []
  387. msg = "Union[arg, ...]: each arg must be a type."
  388. for p in parameters:
  389. if isinstance(p, UnionMeta):
  390. params.extend(p.__union_params__)
  391. else:
  392. params.append(_type_check(p, msg))
  393. # Weed out strict duplicates, preserving the first of each occurrence.
  394. all_params = set(params)
  395. if len(all_params) < len(params):
  396. new_params = []
  397. for t in params:
  398. if t in all_params:
  399. new_params.append(t)
  400. all_params.remove(t)
  401. params = new_params
  402. assert not all_params, all_params
  403. # Weed out subclasses.
  404. # E.g. Union[int, Employee, Manager] == Union[int, Employee].
  405. # If Any or object is present it will be the sole survivor.
  406. # If both Any and object are present, Any wins.
  407. # Never discard type variables, except against Any.
  408. # (In particular, Union[str, AnyStr] != AnyStr.)
  409. all_params = set(params)
  410. for t1 in params:
  411. if t1 is Any:
  412. return Any
  413. if isinstance(t1, TypeVar):
  414. continue
  415. if isinstance(t1, _TypeAlias):
  416. # _TypeAlias is not a real class.
  417. continue
  418. if not isinstance(t1, type):
  419. assert callable(t1) # A callable might sneak through.
  420. continue
  421. if any(isinstance(t2, type) and issubclass(t1, t2)
  422. for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
  423. all_params.remove(t1)
  424. # It's not a union if there's only one type left.
  425. if len(all_params) == 1:
  426. return all_params.pop()
  427. # Create a new class with these params.
  428. self = super().__new__(cls, name, bases, {}, _root=True)
  429. self.__union_params__ = tuple(t for t in params if t in all_params)
  430. self.__union_set_params__ = frozenset(self.__union_params__)
  431. return self
  432. def _eval_type(self, globalns, localns):
  433. p = tuple(_eval_type(t, globalns, localns)
  434. for t in self.__union_params__)
  435. if p == self.__union_params__:
  436. return self
  437. else:
  438. return self.__class__(self.__name__, self.__bases__, {},
  439. p, _root=True)
  440. def _get_type_vars(self, tvars):
  441. if self.__union_params__:
  442. _get_type_vars(self.__union_params__, tvars)
  443. def __repr__(self):
  444. r = super().__repr__()
  445. if self.__union_params__:
  446. r += '[%s]' % (', '.join(_type_repr(t)
  447. for t in self.__union_params__))
  448. return r
  449. def __getitem__(self, parameters):
  450. if self.__union_params__ is not None:
  451. raise TypeError(
  452. "Cannot subscript an existing Union. Use Union[u, t] instead.")
  453. if parameters == ():
  454. raise TypeError("Cannot take a Union of no types.")
  455. if not isinstance(parameters, tuple):
  456. parameters = (parameters,)
  457. return self.__class__(self.__name__, self.__bases__,
  458. dict(self.__dict__), parameters, _root=True)
  459. def __eq__(self, other):
  460. if not isinstance(other, UnionMeta):
  461. return NotImplemented
  462. return self.__union_set_params__ == other.__union_set_params__
  463. def __hash__(self):
  464. return hash(self.__union_set_params__)
  465. def __instancecheck__(self, obj):
  466. raise TypeError("Unions cannot be used with isinstance().")
  467. def __subclasscheck__(self, cls):
  468. if cls is Any:
  469. return True
  470. if self.__union_params__ is None:
  471. return isinstance(cls, UnionMeta)
  472. elif isinstance(cls, UnionMeta):
  473. if cls.__union_params__ is None:
  474. return False
  475. return all(issubclass(c, self) for c in (cls.__union_params__))
  476. elif isinstance(cls, TypeVar):
  477. if cls in self.__union_params__:
  478. return True
  479. if cls.__constraints__:
  480. return issubclass(Union[cls.__constraints__], self)
  481. return False
  482. else:
  483. return any(issubclass(cls, t) for t in self.__union_params__)
  484. class Union(Final, metaclass=UnionMeta, _root=True):
  485. """Union type; Union[X, Y] means either X or Y.
  486. To define a union, use e.g. Union[int, str]. Details:
  487. - The arguments must be types and there must be at least one.
  488. - None as an argument is a special case and is replaced by
  489. type(None).
  490. - Unions of unions are flattened, e.g.::
  491. Union[Union[int, str], float] == Union[int, str, float]
  492. - Unions of a single argument vanish, e.g.::
  493. Union[int] == int # The constructor actually returns int
  494. - Redundant arguments are skipped, e.g.::
  495. Union[int, str, int] == Union[int, str]
  496. - When comparing unions, the argument order is ignored, e.g.::
  497. Union[int, str] == Union[str, int]
  498. - When two arguments have a subclass relationship, the least
  499. derived argument is kept, e.g.::
  500. class Employee: pass
  501. class Manager(Employee): pass
  502. Union[int, Employee, Manager] == Union[int, Employee]
  503. Union[Manager, int, Employee] == Union[int, Employee]
  504. Union[Employee, Manager] == Employee
  505. - Corollary: if Any is present it is the sole survivor, e.g.::
  506. Union[int, Any] == Any
  507. - Similar for object::
  508. Union[int, object] == object
  509. - To cut a tie: Union[object, Any] == Union[Any, object] == Any.
  510. - You cannot subclass or instantiate a union.
  511. - You cannot write Union[X][Y] (what would it mean?).
  512. - You can use Optional[X] as a shorthand for Union[X, None].
  513. """
  514. # Unsubscripted Union type has params set to None.
  515. __union_params__ = None
  516. __union_set_params__ = None
  517. class OptionalMeta(TypingMeta):
  518. """Metaclass for Optional."""
  519. def __new__(cls, name, bases, namespace, _root=False):
  520. return super().__new__(cls, name, bases, namespace, _root=_root)
  521. def __getitem__(self, arg):
  522. arg = _type_check(arg, "Optional[t] requires a single type.")
  523. return Union[arg, type(None)]
  524. class Optional(Final, metaclass=OptionalMeta, _root=True):
  525. """Optional type.
  526. Optional[X] is equivalent to Union[X, type(None)].
  527. """
  528. __slots__ = ()
  529. class TupleMeta(TypingMeta):
  530. """Metaclass for Tuple."""
  531. def __new__(cls, name, bases, namespace, parameters=None,
  532. use_ellipsis=False, _root=False):
  533. self = super().__new__(cls, name, bases, namespace, _root=_root)
  534. self.__tuple_params__ = parameters
  535. self.__tuple_use_ellipsis__ = use_ellipsis
  536. return self
  537. def _get_type_vars(self, tvars):
  538. if self.__tuple_params__:
  539. _get_type_vars(self.__tuple_params__, tvars)
  540. def _eval_type(self, globalns, localns):
  541. tp = self.__tuple_params__
  542. if tp is None:
  543. return self
  544. p = tuple(_eval_type(t, globalns, localns) for t in tp)
  545. if p == self.__tuple_params__:
  546. return self
  547. else:
  548. return self.__class__(self.__name__, self.__bases__, {},
  549. p, _root=True)
  550. def __repr__(self):
  551. r = super().__repr__()
  552. if self.__tuple_params__ is not None:
  553. params = [_type_repr(p) for p in self.__tuple_params__]
  554. if self.__tuple_use_ellipsis__:
  555. params.append('...')
  556. if not params:
  557. params.append('()')
  558. r += '[%s]' % (
  559. ', '.join(params))
  560. return r
  561. def __getitem__(self, parameters):
  562. if self.__tuple_params__ is not None:
  563. raise TypeError("Cannot re-parameterize %r" % (self,))
  564. if not isinstance(parameters, tuple):
  565. parameters = (parameters,)
  566. if len(parameters) == 2 and parameters[1] == Ellipsis:
  567. parameters = parameters[:1]
  568. use_ellipsis = True
  569. msg = "Tuple[t, ...]: t must be a type."
  570. else:
  571. use_ellipsis = False
  572. msg = "Tuple[t0, t1, ...]: each t must be a type."
  573. parameters = tuple(_type_check(p, msg) for p in parameters)
  574. return self.__class__(self.__name__, self.__bases__,
  575. dict(self.__dict__), parameters,
  576. use_ellipsis=use_ellipsis, _root=True)
  577. def __eq__(self, other):
  578. if not isinstance(other, TupleMeta):
  579. return NotImplemented
  580. return (self.__tuple_params__ == other.__tuple_params__ and
  581. self.__tuple_use_ellipsis__ == other.__tuple_use_ellipsis__)
  582. def __hash__(self):
  583. return hash(self.__tuple_params__)
  584. def __instancecheck__(self, obj):
  585. raise TypeError("Tuples cannot be used with isinstance().")
  586. def __subclasscheck__(self, cls):
  587. if cls is Any:
  588. return True
  589. if not isinstance(cls, type):
  590. return super().__subclasscheck__(cls) # To TypeError.
  591. if issubclass(cls, tuple):
  592. return True # Special case.
  593. if not isinstance(cls, TupleMeta):
  594. return super().__subclasscheck__(cls) # False.
  595. if self.__tuple_params__ is None:
  596. return True
  597. if cls.__tuple_params__ is None:
  598. return False # ???
  599. if cls.__tuple_use_ellipsis__ != self.__tuple_use_ellipsis__:
  600. return False
  601. # Covariance.
  602. return (len(self.__tuple_params__) == len(cls.__tuple_params__) and
  603. all(issubclass(x, p)
  604. for x, p in zip(cls.__tuple_params__,
  605. self.__tuple_params__)))
  606. class Tuple(Final, metaclass=TupleMeta, _root=True):
  607. """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
  608. Example: Tuple[T1, T2] is a tuple of two elements corresponding
  609. to type variables T1 and T2. Tuple[int, float, str] is a tuple
  610. of an int, a float and a string.
  611. To specify a variable-length tuple of homogeneous type, use Sequence[T].
  612. """
  613. __slots__ = ()
  614. class CallableMeta(TypingMeta):
  615. """Metaclass for Callable."""
  616. def __new__(cls, name, bases, namespace, _root=False,
  617. args=None, result=None):
  618. if args is None and result is None:
  619. pass # Must be 'class Callable'.
  620. else:
  621. if args is not Ellipsis:
  622. if not isinstance(args, list):
  623. raise TypeError("Callable[args, result]: "
  624. "args must be a list."
  625. " Got %.100r." % (args,))
  626. msg = "Callable[[arg, ...], result]: each arg must be a type."
  627. args = tuple(_type_check(arg, msg) for arg in args)
  628. msg = "Callable[args, result]: result must be a type."
  629. result = _type_check(result, msg)
  630. self = super().__new__(cls, name, bases, namespace, _root=_root)
  631. self.__args__ = args
  632. self.__result__ = result
  633. return self
  634. def _get_type_vars(self, tvars):
  635. if self.__args__:
  636. _get_type_vars(self.__args__, tvars)
  637. def _eval_type(self, globalns, localns):
  638. if self.__args__ is None and self.__result__ is None:
  639. return self
  640. if self.__args__ is Ellipsis:
  641. args = self.__args__
  642. else:
  643. args = [_eval_type(t, globalns, localns) for t in self.__args__]
  644. result = _eval_type(self.__result__, globalns, localns)
  645. if args == self.__args__ and result == self.__result__:
  646. return self
  647. else:
  648. return self.__class__(self.__name__, self.__bases__, {},
  649. args=args, result=result, _root=True)
  650. def __repr__(self):
  651. r = super().__repr__()
  652. if self.__args__ is not None or self.__result__ is not None:
  653. if self.__args__ is Ellipsis:
  654. args_r = '...'
  655. else:
  656. args_r = '[%s]' % ', '.join(_type_repr(t)
  657. for t in self.__args__)
  658. r += '[%s, %s]' % (args_r, _type_repr(self.__result__))
  659. return r
  660. def __getitem__(self, parameters):
  661. if self.__args__ is not None or self.__result__ is not None:
  662. raise TypeError("This Callable type is already parameterized.")
  663. if not isinstance(parameters, tuple) or len(parameters) != 2:
  664. raise TypeError(
  665. "Callable must be used as Callable[[arg, ...], result].")
  666. args, result = parameters
  667. return self.__class__(self.__name__, self.__bases__,
  668. dict(self.__dict__), _root=True,
  669. args=args, result=result)
  670. def __eq__(self, other):
  671. if not isinstance(other, CallableMeta):
  672. return NotImplemented
  673. return (self.__args__ == other.__args__ and
  674. self.__result__ == other.__result__)
  675. def __hash__(self):
  676. return hash(self.__args__) ^ hash(self.__result__)
  677. def __instancecheck__(self, obj):
  678. # For unparametrized Callable we allow this, because
  679. # typing.Callable should be equivalent to
  680. # collections.abc.Callable.
  681. if self.__args__ is None and self.__result__ is None:
  682. return isinstance(obj, collections_abc.Callable)
  683. else:
  684. raise TypeError("Callable[] cannot be used with isinstance().")
  685. def __subclasscheck__(self, cls):
  686. if cls is Any:
  687. return True
  688. if not isinstance(cls, CallableMeta):
  689. return super().__subclasscheck__(cls)
  690. if self.__args__ is None and self.__result__ is None:
  691. return True
  692. # We're not doing covariance or contravariance -- this is *invariance*.
  693. return self == cls
  694. class Callable(Final, metaclass=CallableMeta, _root=True):
  695. """Callable type; Callable[[int], str] is a function of (int) -> str.
  696. The subscription syntax must always be used with exactly two
  697. values: the argument list and the return type. The argument list
  698. must be a list of types; the return type must be a single type.
  699. There is no syntax to indicate optional or keyword arguments,
  700. such function types are rarely used as callback types.
  701. """
  702. __slots__ = ()
  703. def _gorg(a):
  704. """Return the farthest origin of a generic class."""
  705. assert isinstance(a, GenericMeta)
  706. while a.__origin__ is not None:
  707. a = a.__origin__
  708. return a
  709. def _geqv(a, b):
  710. """Return whether two generic classes are equivalent.
  711. The intention is to consider generic class X and any of its
  712. parameterized forms (X[T], X[int], etc.) as equivalent.
  713. However, X is not equivalent to a subclass of X.
  714. The relation is reflexive, symmetric and transitive.
  715. """
  716. assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
  717. # Reduce each to its origin.
  718. return _gorg(a) is _gorg(b)
  719. def _next_in_mro(cls):
  720. """Helper for Generic.__new__.
  721. Returns the class after the last occurrence of Generic or
  722. Generic[...] in cls.__mro__.
  723. """
  724. next_in_mro = object
  725. # Look for the last occurrence of Generic or Generic[...].
  726. for i, c in enumerate(cls.__mro__[:-1]):
  727. if isinstance(c, GenericMeta) and _gorg(c) is Generic:
  728. next_in_mro = cls.__mro__[i+1]
  729. return next_in_mro
  730. class GenericMeta(TypingMeta, abc.ABCMeta):
  731. """Metaclass for generic types."""
  732. def __new__(cls, name, bases, namespace,
  733. tvars=None, args=None, origin=None, extra=None):
  734. self = super().__new__(cls, name, bases, namespace, _root=True)
  735. if tvars is not None:
  736. # Called from __getitem__() below.
  737. assert origin is not None
  738. assert all(isinstance(t, TypeVar) for t in tvars), tvars
  739. else:
  740. # Called from class statement.
  741. assert tvars is None, tvars
  742. assert args is None, args
  743. assert origin is None, origin
  744. # Get the full set of tvars from the bases.
  745. tvars = _type_vars(bases)
  746. # Look for Generic[T1, ..., Tn].
  747. # If found, tvars must be a subset of it.
  748. # If not found, tvars is it.
  749. # Also check for and reject plain Generic,
  750. # and reject multiple Generic[...].
  751. gvars = None
  752. for base in bases:
  753. if base is Generic:
  754. raise TypeError("Cannot inherit from plain Generic")
  755. if (isinstance(base, GenericMeta) and
  756. base.__origin__ is Generic):
  757. if gvars is not None:
  758. raise TypeError(
  759. "Cannot inherit from Generic[...] multiple types.")
  760. gvars = base.__parameters__
  761. if gvars is None:
  762. gvars = tvars
  763. else:
  764. tvarset = set(tvars)
  765. gvarset = set(gvars)
  766. if not tvarset <= gvarset:
  767. raise TypeError(
  768. "Some type variables (%s) "
  769. "are not listed in Generic[%s]" %
  770. (", ".join(str(t) for t in tvars if t not in gvarset),
  771. ", ".join(str(g) for g in gvars)))
  772. tvars = gvars
  773. self.__parameters__ = tvars
  774. self.__args__ = args
  775. self.__origin__ = origin
  776. self.__extra__ = extra
  777. # Speed hack (https://github.com/python/typing/issues/196).
  778. self.__next_in_mro__ = _next_in_mro(self)
  779. return self
  780. def _get_type_vars(self, tvars):
  781. if self.__origin__ and self.__parameters__:
  782. _get_type_vars(self.__parameters__, tvars)
  783. def __repr__(self):
  784. if self.__origin__ is not None:
  785. r = repr(self.__origin__)
  786. else:
  787. r = super().__repr__()
  788. if self.__args__:
  789. r += '[%s]' % (
  790. ', '.join(_type_repr(p) for p in self.__args__))
  791. if self.__parameters__:
  792. r += '<%s>' % (
  793. ', '.join(_type_repr(p) for p in self.__parameters__))
  794. return r
  795. def __eq__(self, other):
  796. if not isinstance(other, GenericMeta):
  797. return NotImplemented
  798. if self.__origin__ is not None:
  799. return (self.__origin__ is other.__origin__ and
  800. self.__args__ == other.__args__ and
  801. self.__parameters__ == other.__parameters__)
  802. else:
  803. return self is other
  804. def __hash__(self):
  805. return hash((self.__name__, self.__parameters__))
  806. def __getitem__(self, params):
  807. if not isinstance(params, tuple):
  808. params = (params,)
  809. if not params:
  810. raise TypeError(
  811. "Parameter list to %s[...] cannot be empty" % _qualname(self))
  812. msg = "Parameters to generic types must be types."
  813. params = tuple(_type_check(p, msg) for p in params)
  814. if self is Generic:
  815. # Generic can only be subscripted with unique type variables.
  816. if not all(isinstance(p, TypeVar) for p in params):
  817. raise TypeError(
  818. "Parameters to Generic[...] must all be type variables")
  819. if len(set(params)) != len(params):
  820. raise TypeError(
  821. "Parameters to Generic[...] must all be unique")
  822. tvars = params
  823. args = None
  824. elif self is _Protocol:
  825. # _Protocol is internal, don't check anything.
  826. tvars = params
  827. args = None
  828. elif self.__origin__ in (Generic, _Protocol):
  829. # Can't subscript Generic[...] or _Protocol[...].
  830. raise TypeError("Cannot subscript already-subscripted %s" %
  831. repr(self))
  832. else:
  833. # Subscripting a regular Generic subclass.
  834. if not self.__parameters__:
  835. raise TypeError("%s is not a generic class" % repr(self))
  836. alen = len(params)
  837. elen = len(self.__parameters__)
  838. if alen != elen:
  839. raise TypeError(
  840. "Too %s parameters for %s; actual %s, expected %s" %
  841. ("many" if alen > elen else "few", repr(self), alen, elen))
  842. tvars = _type_vars(params)
  843. args = params
  844. return self.__class__(self.__name__,
  845. (self,) + self.__bases__,
  846. dict(self.__dict__),
  847. tvars=tvars,
  848. args=args,
  849. origin=self,
  850. extra=self.__extra__)
  851. def __instancecheck__(self, instance):
  852. # Since we extend ABC.__subclasscheck__ and
  853. # ABC.__instancecheck__ inlines the cache checking done by the
  854. # latter, we must extend __instancecheck__ too. For simplicity
  855. # we just skip the cache check -- instance checks for generic
  856. # classes are supposed to be rare anyways.
  857. return self.__subclasscheck__(instance.__class__)
  858. def __subclasscheck__(self, cls):
  859. if cls is Any:
  860. return True
  861. if isinstance(cls, GenericMeta):
  862. # For a class C(Generic[T]) where T is co-variant,
  863. # C[X] is a subclass of C[Y] iff X is a subclass of Y.
  864. origin = self.__origin__
  865. if origin is not None and origin is cls.__origin__:
  866. assert len(self.__args__) == len(origin.__parameters__)
  867. assert len(cls.__args__) == len(origin.__parameters__)
  868. for p_self, p_cls, p_origin in zip(self.__args__,
  869. cls.__args__,
  870. origin.__parameters__):
  871. if isinstance(p_origin, TypeVar):
  872. if p_origin.__covariant__:
  873. # Covariant -- p_cls must be a subclass of p_self.
  874. if not issubclass(p_cls, p_self):
  875. break
  876. elif p_origin.__contravariant__:
  877. # Contravariant. I think it's the opposite. :-)
  878. if not issubclass(p_self, p_cls):
  879. break
  880. else:
  881. # Invariant -- p_cls and p_self must equal.
  882. if p_self != p_cls:
  883. break
  884. else:
  885. # If the origin's parameter is not a typevar,
  886. # insist on invariance.
  887. if p_self != p_cls:
  888. break
  889. else:
  890. return True
  891. # If we break out of the loop, the superclass gets a chance.
  892. if super().__subclasscheck__(cls):
  893. return True
  894. if self.__extra__ is None or isinstance(cls, GenericMeta):
  895. return False
  896. return issubclass(cls, self.__extra__)
  897. # Prevent checks for Generic to crash when defining Generic.
  898. Generic = None
  899. class Generic(metaclass=GenericMeta):
  900. """Abstract base class for generic types.
  901. A generic type is typically declared by inheriting from an
  902. instantiation of this class with one or more type variables.
  903. For example, a generic mapping type might be defined as::
  904. class Mapping(Generic[KT, VT]):
  905. def __getitem__(self, key: KT) -> VT:
  906. ...
  907. # Etc.
  908. This class can then be used as follows::
  909. def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
  910. try:
  911. return mapping[key]
  912. except KeyError:
  913. return default
  914. """
  915. __slots__ = ()
  916. def __new__(cls, *args, **kwds):
  917. if cls.__origin__ is None:
  918. return cls.__next_in_mro__.__new__(cls)
  919. else:
  920. origin = _gorg(cls)
  921. obj = cls.__next_in_mro__.__new__(origin)
  922. obj.__init__(*args, **kwds)
  923. return obj
  924. def cast(typ, val):
  925. """Cast a value to a type.
  926. This returns the value unchanged. To the type checker this
  927. signals that the return value has the designated type, but at
  928. runtime we intentionally don't check anything (we want this
  929. to be as fast as possible).
  930. """
  931. return val
  932. def _get_defaults(func):
  933. """Internal helper to extract the default arguments, by name."""
  934. code = func.__code__
  935. pos_count = code.co_argcount
  936. arg_names = code.co_varnames
  937. arg_names = arg_names[:pos_count]
  938. defaults = func.__defaults__ or ()
  939. kwdefaults = func.__kwdefaults__
  940. res = dict(kwdefaults) if kwdefaults else {}
  941. pos_offset = pos_count - len(defaults)
  942. for name, value in zip(arg_names[pos_offset:], defaults):
  943. assert name not in res
  944. res[name] = value
  945. return res
  946. def get_type_hints(obj, globalns=None, localns=None):
  947. """Return type hints for a function or method object.
  948. This is often the same as obj.__annotations__, but it handles
  949. forward references encoded as string literals, and if necessary
  950. adds Optional[t] if a default value equal to None is set.
  951. BEWARE -- the behavior of globalns and localns is counterintuitive
  952. (unless you are familiar with how eval() and exec() work). The
  953. search order is locals first, then globals.
  954. - If no dict arguments are passed, an attempt is made to use the
  955. globals from obj, and these are also used as the locals. If the
  956. object does not appear to have globals, an exception is raised.
  957. - If one dict argument is passed, it is used for both globals and
  958. locals.
  959. - If two dict arguments are passed, they specify globals and
  960. locals, respectively.
  961. """
  962. if getattr(obj, '__no_type_check__', None):
  963. return {}
  964. if globalns is None:
  965. globalns = getattr(obj, '__globals__', {})
  966. if localns is None:
  967. localns = globalns
  968. elif localns is None:
  969. localns = globalns
  970. defaults = _get_defaults(obj)
  971. hints = dict(obj.__annotations__)
  972. for name, value in hints.items():
  973. if isinstance(value, str):
  974. value = _ForwardRef(value)
  975. value = _eval_type(value, globalns, localns)
  976. if name in defaults and defaults[name] is None:
  977. value = Optional[value]
  978. hints[name] = value
  979. return hints
  980. def no_type_check(arg):
  981. """Decorator to indicate that annotations are not type hints.
  982. The argument must be a class or function; if it is a class, it
  983. applies recursively to all methods defined in that class (but not
  984. to methods defined in its superclasses or subclasses).
  985. This mutates the function(s) in place.
  986. """
  987. if isinstance(arg, type):
  988. for obj in arg.__dict__.values():
  989. if isinstance(obj, types.FunctionType):
  990. obj.__no_type_check__ = True
  991. else:
  992. arg.__no_type_check__ = True
  993. return arg
  994. def no_type_check_decorator(decorator):
  995. """Decorator to give another decorator the @no_type_check effect.
  996. This wraps the decorator with something that wraps the decorated
  997. function in @no_type_check.
  998. """
  999. @functools.wraps(decorator)
  1000. def wrapped_decorator(*args, **kwds):
  1001. func = decorator(*args, **kwds)
  1002. func = no_type_check(func)
  1003. return func
  1004. return wrapped_decorator
  1005. def _overload_dummy(*args, **kwds):
  1006. """Helper for @overload to raise when called."""
  1007. raise NotImplementedError(
  1008. "You should not call an overloaded function. "
  1009. "A series of @overload-decorated functions "
  1010. "outside a stub module should always be followed "
  1011. "by an implementation that is not @overload-ed.")
  1012. def overload(func):
  1013. """Decorator for overloaded functions/methods.
  1014. In a stub file, place two or more stub definitions for the same
  1015. function in a row, each decorated with @overload. For example:
  1016. @overload
  1017. def utf8(value: None) -> None: ...
  1018. @overload
  1019. def utf8(value: bytes) -> bytes: ...
  1020. @overload
  1021. def utf8(value: str) -> bytes: ...
  1022. In a non-stub file (i.e. a regular .py file), do the same but
  1023. follow it with an implementation. The implementation should *not*
  1024. be decorated with @overload. For example:
  1025. @overload
  1026. def utf8(value: None) -> None: ...
  1027. @overload
  1028. def utf8(value: bytes) -> bytes: ...
  1029. @overload
  1030. def utf8(value: str) -> bytes: ...
  1031. def utf8(value):
  1032. # implementation goes here
  1033. """
  1034. return _overload_dummy
  1035. class _ProtocolMeta(GenericMeta):
  1036. """Internal metaclass for _Protocol.
  1037. This exists so _Protocol classes can be generic without deriving
  1038. from Generic.
  1039. """
  1040. def __instancecheck__(self, obj):
  1041. raise TypeError("Protocols cannot be used with isinstance().")
  1042. def __subclasscheck__(self, cls):
  1043. if not self._is_protocol:
  1044. # No structural checks since this isn't a protocol.
  1045. return NotImplemented
  1046. if self is _Protocol:
  1047. # Every class is a subclass of the empty protocol.
  1048. return True
  1049. # Find all attributes defined in the protocol.
  1050. attrs = self._get_protocol_attrs()
  1051. for attr in attrs:
  1052. if not any(attr in d.__dict__ for d in cls.__mro__):
  1053. return False
  1054. return True
  1055. def _get_protocol_attrs(self):
  1056. # Get all Protocol base classes.
  1057. protocol_bases = []
  1058. for c in self.__mro__:
  1059. if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
  1060. protocol_bases.append(c)
  1061. # Get attributes included in protocol.
  1062. attrs = set()
  1063. for base in protocol_bases:
  1064. for attr in base.__dict__.keys():
  1065. # Include attributes not defined in any non-protocol bases.
  1066. for c in self.__mro__:
  1067. if (c is not base and attr in c.__dict__ and
  1068. not getattr(c, '_is_protocol', False)):
  1069. break
  1070. else:
  1071. if (not attr.startswith('_abc_') and
  1072. attr != '__abstractmethods__' and
  1073. attr != '_is_protocol' and
  1074. attr != '__dict__' and
  1075. attr != '__args__' and
  1076. attr != '__slots__' and
  1077. attr != '_get_protocol_attrs' and
  1078. attr != '__next_in_mro__' and
  1079. attr != '__parameters__' and
  1080. attr != '__origin__' and
  1081. attr != '__extra__' and
  1082. attr != '__module__'):
  1083. attrs.add(attr)
  1084. return attrs
  1085. class _Protocol(metaclass=_ProtocolMeta):
  1086. """Internal base class for protocol classes.
  1087. This implements a simple-minded structural isinstance check
  1088. (similar but more general than the one-offs in collections.abc
  1089. such as Hashable).
  1090. """
  1091. __slots__ = ()
  1092. _is_protocol = True
  1093. # Various ABCs mimicking those in collections.abc.
  1094. # A few are simply re-exported for completeness.
  1095. Hashable = collections_abc.Hashable # Not generic.
  1096. if hasattr(collections_abc, 'Awaitable'):
  1097. class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
  1098. __slots__ = ()
  1099. else:
  1100. Awaitable = None
  1101. if hasattr(collections_abc, 'AsyncIterable'):
  1102. class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
  1103. __slots__ = ()
  1104. class AsyncIterator(AsyncIterable[T_co],
  1105. extra=collections_abc.AsyncIterator):
  1106. __slots__ = ()
  1107. else:
  1108. AsyncIterable = None
  1109. AsyncIterator = None
  1110. class Iterable(Generic[T_co], extra=collections_abc.Iterable):
  1111. __slots__ = ()
  1112. class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
  1113. __slots__ = ()
  1114. class SupportsInt(_Protocol):
  1115. __slots__ = ()
  1116. @abstractmethod
  1117. def __int__(self) -> int:
  1118. pass
  1119. class SupportsFloat(_Protocol):
  1120. __slots__ = ()
  1121. @abstractmethod
  1122. def __float__(self) -> float:
  1123. pass
  1124. class SupportsComplex(_Protocol):
  1125. __slots__ = ()
  1126. @abstractmethod
  1127. def __complex__(self) -> complex:
  1128. pass
  1129. class SupportsBytes(_Protocol):
  1130. __slots__ = ()
  1131. @abstractmethod
  1132. def __bytes__(self) -> bytes:
  1133. pass
  1134. class SupportsAbs(_Protocol[T_co]):
  1135. __slots__ = ()
  1136. @abstractmethod
  1137. def __abs__(self) -> T_co:
  1138. pass
  1139. class SupportsRound(_Protocol[T_co]):
  1140. __slots__ = ()
  1141. @abstractmethod
  1142. def __round__(self, ndigits: int = 0) -> T_co:
  1143. pass
  1144. if hasattr(collections_abc, 'Reversible'):
  1145. class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
  1146. __slots__ = ()
  1147. else:
  1148. class Reversible(_Protocol[T_co]):
  1149. __slots__ = ()
  1150. @abstractmethod
  1151. def __reversed__(self) -> 'Iterator[T_co]':
  1152. pass
  1153. Sized = collections_abc.Sized # Not generic.
  1154. class Container(Generic[T_co], extra=collections_abc.Container):
  1155. __slots__ = ()
  1156. # Callable was defined earlier.
  1157. class AbstractSet(Sized, Iterable[T_co], Container[T_co],
  1158. extra=collections_abc.Set):
  1159. pass
  1160. class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
  1161. pass
  1162. # NOTE: Only the value type is covariant.
  1163. class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
  1164. extra=collections_abc.Mapping):
  1165. pass
  1166. class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
  1167. pass
  1168. if hasattr(collections_abc, 'Reversible'):
  1169. class Sequence(Sized, Reversible[T_co], Container[T_co],
  1170. extra=collections_abc.Sequence):
  1171. pass
  1172. else:
  1173. class Sequence(Sized, Iterable[T_co], Container[T_co],
  1174. extra=collections_abc.Sequence):
  1175. pass
  1176. class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
  1177. pass
  1178. class ByteString(Sequence[int], extra=collections_abc.ByteString):
  1179. pass
  1180. ByteString.register(type(memoryview(b'')))
  1181. class List(list, MutableSequence[T], extra=list):
  1182. def __new__(cls, *args, **kwds):
  1183. if _geqv(cls, List):
  1184. raise TypeError("Type List cannot be instantiated; "
  1185. "use list() instead")
  1186. return list.__new__(cls, *args, **kwds)
  1187. class Set(set, MutableSet[T], extra=set):
  1188. def __new__(cls, *args, **kwds):
  1189. if _geqv(cls, Set):
  1190. raise TypeError("Type Set cannot be instantiated; "
  1191. "use set() instead")
  1192. return set.__new__(cls, *args, **kwds)
  1193. class _FrozenSetMeta(GenericMeta):
  1194. """This metaclass ensures set is not a subclass of FrozenSet.
  1195. Without this metaclass, set would be considered a subclass of
  1196. FrozenSet, because FrozenSet.__extra__ is collections.abc.Set, and
  1197. set is a subclass of that.
  1198. """
  1199. def __subclasscheck__(self, cls):
  1200. if issubclass(cls, Set):
  1201. return False
  1202. return super().__subclasscheck__(cls)
  1203. class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta,
  1204. extra=frozenset):
  1205. __slots__ = ()
  1206. def __new__(cls, *args, **kwds):
  1207. if _geqv(cls, FrozenSet):
  1208. raise TypeError("Type FrozenSet cannot be instantiated; "
  1209. "use frozenset() instead")
  1210. return frozenset.__new__(cls, *args, **kwds)
  1211. class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
  1212. pass
  1213. class KeysView(MappingView[KT], AbstractSet[KT],
  1214. extra=collections_abc.KeysView):
  1215. pass
  1216. class ItemsView(MappingView[Tuple[KT, VT_co]],
  1217. AbstractSet[Tuple[KT, VT_co]],
  1218. Generic[KT, VT_co],
  1219. extra=collections_abc.ItemsView):
  1220. pass
  1221. class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
  1222. pass
  1223. if hasattr(contextlib, 'AbstractContextManager'):
  1224. class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
  1225. __slots__ = ()
  1226. __all__.append('ContextManager')
  1227. class Dict(dict, MutableMapping[KT, VT], extra=dict):
  1228. def __new__(cls, *args, **kwds):
  1229. if _geqv(cls, Dict):
  1230. raise TypeError("Type Dict cannot be instantiated; "
  1231. "use dict() instead")
  1232. return dict.__new__(cls, *args, **kwds)
  1233. class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
  1234. extra=collections.defaultdict):
  1235. def __new__(cls, *args, **kwds):
  1236. if _geqv(cls, DefaultDict):
  1237. raise TypeError("Type DefaultDict cannot be instantiated; "
  1238. "use collections.defaultdict() instead")
  1239. return collections.defaultdict.__new__(cls, *args, **kwds)
  1240. # Determine what base class to use for Generator.
  1241. if hasattr(collections_abc, 'Generator'):
  1242. # Sufficiently recent versions of 3.5 have a Generator ABC.
  1243. _G_base = collections_abc.Generator
  1244. else:
  1245. # Fall back on the exact type.
  1246. _G_base = types.GeneratorType
  1247. class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
  1248. extra=_G_base):
  1249. __slots__ = ()
  1250. def __new__(cls, *args, **kwds):
  1251. if _geqv(cls, Generator):
  1252. raise TypeError("Type Generator cannot be instantiated; "
  1253. "create a subclass instead")
  1254. return super().__new__(cls, *args, **kwds)
  1255. # Internal type variable used for Type[].
  1256. CT = TypeVar('CT', covariant=True, bound=type)
  1257. # This is not a real generic class. Don't use outside annotations.
  1258. class Type(type, Generic[CT], extra=type):
  1259. """A special construct usable to annotate class objects.
  1260. For example, suppose we have the following classes::
  1261. class User: ... # Abstract base for User classes
  1262. class BasicUser(User): ...
  1263. class ProUser(User): ...
  1264. class TeamUser(User): ...
  1265. And a function that takes a class argument that's a subclass of
  1266. User and returns an instance of the corresponding class::
  1267. U = TypeVar('U', bound=User)
  1268. def new_user(user_class: Type[U]) -> U:
  1269. user = user_class()
  1270. # (Here we could write the user object to a database)
  1271. return user
  1272. joe = new_user(BasicUser)
  1273. At this point the type checker knows that joe has type BasicUser.
  1274. """
  1275. def NamedTuple(typename, fields):
  1276. """Typed version of namedtuple.
  1277. Usage::
  1278. Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)])
  1279. This is equivalent to::
  1280. Employee = collections.namedtuple('Employee', ['name', 'id'])
  1281. The resulting class has one extra attribute: _field_types,
  1282. giving a dict mapping field names to types. (The field names
  1283. are in the _fields attribute, which is part of the namedtuple
  1284. API.)
  1285. """
  1286. fields = [(n, t) for n, t in fields]
  1287. cls = collections.namedtuple(typename, [n for n, t in fields])
  1288. cls._field_types = dict(fields)
  1289. # Set the module to the caller's module (otherwise it'd be 'typing').
  1290. try:
  1291. cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
  1292. except (AttributeError, ValueError):
  1293. pass
  1294. return cls
  1295. def NewType(name, tp):
  1296. """NewType creates simple unique types with almost zero
  1297. runtime overhead. NewType(name, tp) is considered a subtype of tp
  1298. by static type checkers. At runtime, NewType(name, tp) returns
  1299. a dummy function that simply returns its argument. Usage::
  1300. UserId = NewType('UserId', int)
  1301. def name_by_id(user_id: UserId) -> str:
  1302. ...
  1303. UserId('user') # Fails type check
  1304. name_by_id(42) # Fails type check
  1305. name_by_id(UserId(42)) # OK
  1306. num = UserId(5) + 1 # type: int
  1307. """
  1308. def new_type(x):
  1309. return x
  1310. new_type.__name__ = name
  1311. new_type.__supertype__ = tp
  1312. return new_type
  1313. # Python-version-specific alias (Python 2: unicode; Python 3: str)
  1314. Text = str
  1315. # Constant that's True when type checking, but False here.
  1316. TYPE_CHECKING = False
  1317. class IO(Generic[AnyStr]):
  1318. """Generic base class for TextIO and BinaryIO.
  1319. This is an abstract, generic version of the return of open().
  1320. NOTE: This does not distinguish between the different possible
  1321. classes (text vs. binary, read vs. write vs. read/write,
  1322. append-only, unbuffered). The TextIO and BinaryIO subclasses
  1323. below capture the distinctions between text vs. binary, which is
  1324. pervasive in the interface; however we currently do not offer a
  1325. way to track the other distinctions in the type system.
  1326. """
  1327. __slots__ = ()
  1328. @abstractproperty
  1329. def mode(self) -> str:
  1330. pass
  1331. @abstractproperty
  1332. def name(self) -> str:
  1333. pass
  1334. @abstractmethod
  1335. def close(self) -> None:
  1336. pass
  1337. @abstractmethod
  1338. def closed(self) -> bool:
  1339. pass
  1340. @abstractmethod
  1341. def fileno(self) -> int:
  1342. pass
  1343. @abstractmethod
  1344. def flush(self) -> None:
  1345. pass
  1346. @abstractmethod
  1347. def isatty(self) -> bool:
  1348. pass
  1349. @abstractmethod
  1350. def read(self, n: int = -1) -> AnyStr:
  1351. pass
  1352. @abstractmethod
  1353. def readable(self) -> bool:
  1354. pass
  1355. @abstractmethod
  1356. def readline(self, limit: int = -1) -> AnyStr:
  1357. pass
  1358. @abstractmethod
  1359. def readlines(self, hint: int = -1) -> List[AnyStr]:
  1360. pass
  1361. @abstractmethod
  1362. def seek(self, offset: int, whence: int = 0) -> int:
  1363. pass
  1364. @abstractmethod
  1365. def seekable(self) -> bool:
  1366. pass
  1367. @abstractmethod
  1368. def tell(self) -> int:
  1369. pass
  1370. @abstractmethod
  1371. def truncate(self, size: int = None) -> int:
  1372. pass
  1373. @abstractmethod
  1374. def writable(self) -> bool:
  1375. pass
  1376. @abstractmethod
  1377. def write(self, s: AnyStr) -> int:
  1378. pass
  1379. @abstractmethod
  1380. def writelines(self, lines: List[AnyStr]) -> None:
  1381. pass
  1382. @abstractmethod
  1383. def __enter__(self) -> 'IO[AnyStr]':
  1384. pass
  1385. @abstractmethod
  1386. def __exit__(self, type, value, traceback) -> None:
  1387. pass
  1388. class BinaryIO(IO[bytes]):
  1389. """Typed version of the return of open() in binary mode."""
  1390. __slots__ = ()
  1391. @abstractmethod
  1392. def write(self, s: Union[bytes, bytearray]) -> int:
  1393. pass
  1394. @abstractmethod
  1395. def __enter__(self) -> 'BinaryIO':
  1396. pass
  1397. class TextIO(IO[str]):
  1398. """Typed version of the return of open() in text mode."""
  1399. __slots__ = ()
  1400. @abstractproperty
  1401. def buffer(self) -> BinaryIO:
  1402. pass
  1403. @abstractproperty
  1404. def encoding(self) -> str:
  1405. pass
  1406. @abstractproperty
  1407. def errors(self) -> str:
  1408. pass
  1409. @abstractproperty
  1410. def line_buffering(self) -> bool:
  1411. pass
  1412. @abstractproperty
  1413. def newlines(self) -> Any:
  1414. pass
  1415. @abstractmethod
  1416. def __enter__(self) -> 'TextIO':
  1417. pass
  1418. class io:
  1419. """Wrapper namespace for IO generic classes."""
  1420. __all__ = ['IO', 'TextIO', 'BinaryIO']
  1421. IO = IO
  1422. TextIO = TextIO
  1423. BinaryIO = BinaryIO
  1424. io.__name__ = __name__ + '.io'
  1425. sys.modules[io.__name__] = io
  1426. Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
  1427. lambda p: p.pattern)
  1428. Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
  1429. lambda m: m.re.pattern)
  1430. class re:
  1431. """Wrapper namespace for re type aliases."""
  1432. __all__ = ['Pattern', 'Match']
  1433. Pattern = Pattern
  1434. Match = Match
  1435. re.__name__ = __name__ + '.re'
  1436. sys.modules[re.__name__] = re