typing.py 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550
  1. from __future__ import absolute_import, unicode_literals
  2. import abc
  3. from abc import abstractmethod, abstractproperty
  4. import collections
  5. import functools
  6. import re as stdlib_re # Avoid confusion with the re we export.
  7. import sys
  8. import types
  9. import copy
  10. try:
  11. import collections.abc as collections_abc
  12. except ImportError:
  13. import collections as collections_abc # Fallback for PY3.2.
  14. # Please keep __all__ alphabetized within each category.
  15. __all__ = [
  16. # Super-special typing primitives.
  17. 'Any',
  18. 'Callable',
  19. 'ClassVar',
  20. 'Final',
  21. 'Generic',
  22. 'Literal',
  23. 'Optional',
  24. 'Protocol',
  25. 'Tuple',
  26. 'Type',
  27. 'TypeVar',
  28. 'Union',
  29. # ABCs (from collections.abc).
  30. 'AbstractSet', # collections.abc.Set.
  31. 'GenericMeta', # subclass of abc.ABCMeta and a metaclass
  32. # for 'Generic' and ABCs below.
  33. 'ByteString',
  34. 'Container',
  35. 'ContextManager',
  36. 'Hashable',
  37. 'ItemsView',
  38. 'Iterable',
  39. 'Iterator',
  40. 'KeysView',
  41. 'Mapping',
  42. 'MappingView',
  43. 'MutableMapping',
  44. 'MutableSequence',
  45. 'MutableSet',
  46. 'Sequence',
  47. 'Sized',
  48. 'ValuesView',
  49. # Structural checks, a.k.a. protocols.
  50. 'Reversible',
  51. 'SupportsAbs',
  52. 'SupportsComplex',
  53. 'SupportsFloat',
  54. 'SupportsIndex',
  55. 'SupportsInt',
  56. # Concrete collection types.
  57. 'Counter',
  58. 'Deque',
  59. 'Dict',
  60. 'DefaultDict',
  61. 'List',
  62. 'Set',
  63. 'FrozenSet',
  64. 'NamedTuple', # Not really a type.
  65. 'TypedDict', # Not really a type.
  66. 'Generator',
  67. # One-off things.
  68. 'AnyStr',
  69. 'cast',
  70. 'final',
  71. 'get_type_hints',
  72. 'NewType',
  73. 'no_type_check',
  74. 'no_type_check_decorator',
  75. 'NoReturn',
  76. 'overload',
  77. 'runtime_checkable',
  78. 'Text',
  79. 'TYPE_CHECKING',
  80. ]
  81. # The pseudo-submodules 're' and 'io' are part of the public
  82. # namespace, but excluded from __all__ because they might stomp on
  83. # legitimate imports of those modules.
  84. def _qualname(x):
  85. if sys.version_info[:2] >= (3, 3):
  86. return x.__qualname__
  87. else:
  88. # Fall back to just name.
  89. return x.__name__
  90. def _trim_name(nm):
  91. whitelist = ('_TypeAlias', '_ForwardRef', '_TypingBase', '_FinalTypingBase')
  92. if nm.startswith('_') and nm not in whitelist:
  93. nm = nm[1:]
  94. return nm
  95. class TypingMeta(type):
  96. """Metaclass for most types defined in typing module
  97. (not a part of public API).
  98. This also defines a dummy constructor (all the work for most typing
  99. constructs is done in __new__) and a nicer repr().
  100. """
  101. _is_protocol = False
  102. def __new__(cls, name, bases, namespace):
  103. return super(TypingMeta, cls).__new__(cls, str(name), bases, namespace)
  104. @classmethod
  105. def assert_no_subclassing(cls, bases):
  106. for base in bases:
  107. if isinstance(base, cls):
  108. raise TypeError("Cannot subclass %s" %
  109. (', '.join(map(_type_repr, bases)) or '()'))
  110. def __init__(self, *args, **kwds):
  111. pass
  112. def _eval_type(self, globalns, localns):
  113. """Override this in subclasses to interpret forward references.
  114. For example, List['C'] is internally stored as
  115. List[_ForwardRef('C')], which should evaluate to List[C],
  116. where C is an object found in globalns or localns (searching
  117. localns first, of course).
  118. """
  119. return self
  120. def _get_type_vars(self, tvars):
  121. pass
  122. def __repr__(self):
  123. qname = _trim_name(_qualname(self))
  124. return '%s.%s' % (self.__module__, qname)
  125. class _TypingBase(object):
  126. """Internal indicator of special typing constructs."""
  127. __metaclass__ = TypingMeta
  128. __slots__ = ('__weakref__',)
  129. def __init__(self, *args, **kwds):
  130. pass
  131. def __new__(cls, *args, **kwds):
  132. """Constructor.
  133. This only exists to give a better error message in case
  134. someone tries to subclass a special typing object (not a good idea).
  135. """
  136. if (len(args) == 3 and
  137. isinstance(args[0], str) and
  138. isinstance(args[1], tuple)):
  139. # Close enough.
  140. raise TypeError("Cannot subclass %r" % cls)
  141. return super(_TypingBase, cls).__new__(cls)
  142. # Things that are not classes also need these.
  143. def _eval_type(self, globalns, localns):
  144. return self
  145. def _get_type_vars(self, tvars):
  146. pass
  147. def __repr__(self):
  148. cls = type(self)
  149. qname = _trim_name(_qualname(cls))
  150. return '%s.%s' % (cls.__module__, qname)
  151. def __call__(self, *args, **kwds):
  152. raise TypeError("Cannot instantiate %r" % type(self))
  153. class _FinalTypingBase(_TypingBase):
  154. """Internal mix-in class to prevent instantiation.
  155. Prevents instantiation unless _root=True is given in class call.
  156. It is used to create pseudo-singleton instances Any, Union, Optional, etc.
  157. """
  158. __slots__ = ()
  159. def __new__(cls, *args, **kwds):
  160. self = super(_FinalTypingBase, cls).__new__(cls, *args, **kwds)
  161. if '_root' in kwds and kwds['_root'] is True:
  162. return self
  163. raise TypeError("Cannot instantiate %r" % cls)
  164. def __reduce__(self):
  165. return _trim_name(type(self).__name__)
  166. class _ForwardRef(_TypingBase):
  167. """Internal wrapper to hold a forward reference."""
  168. __slots__ = ('__forward_arg__', '__forward_code__',
  169. '__forward_evaluated__', '__forward_value__')
  170. def __init__(self, arg):
  171. super(_ForwardRef, self).__init__(arg)
  172. if not isinstance(arg, basestring):
  173. raise TypeError('Forward reference must be a string -- got %r' % (arg,))
  174. try:
  175. code = compile(arg, '<string>', 'eval')
  176. except SyntaxError:
  177. raise SyntaxError('Forward reference must be an expression -- got %r' %
  178. (arg,))
  179. self.__forward_arg__ = arg
  180. self.__forward_code__ = code
  181. self.__forward_evaluated__ = False
  182. self.__forward_value__ = None
  183. def _eval_type(self, globalns, localns):
  184. if not self.__forward_evaluated__ or localns is not globalns:
  185. if globalns is None and localns is None:
  186. globalns = localns = {}
  187. elif globalns is None:
  188. globalns = localns
  189. elif localns is None:
  190. localns = globalns
  191. self.__forward_value__ = _type_check(
  192. eval(self.__forward_code__, globalns, localns),
  193. "Forward references must evaluate to types.")
  194. self.__forward_evaluated__ = True
  195. return self.__forward_value__
  196. def __eq__(self, other):
  197. if not isinstance(other, _ForwardRef):
  198. return NotImplemented
  199. return (self.__forward_arg__ == other.__forward_arg__ and
  200. self.__forward_value__ == other.__forward_value__)
  201. def __hash__(self):
  202. return hash((self.__forward_arg__, self.__forward_value__))
  203. def __instancecheck__(self, obj):
  204. raise TypeError("Forward references cannot be used with isinstance().")
  205. def __subclasscheck__(self, cls):
  206. raise TypeError("Forward references cannot be used with issubclass().")
  207. def __repr__(self):
  208. return '_ForwardRef(%r)' % (self.__forward_arg__,)
  209. class _TypeAlias(_TypingBase):
  210. """Internal helper class for defining generic variants of concrete types.
  211. Note that this is not a type; let's call it a pseudo-type. It cannot
  212. be used in instance and subclass checks in parameterized form, i.e.
  213. ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning
  214. ``False``.
  215. """
  216. __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
  217. def __init__(self, name, type_var, impl_type, type_checker):
  218. """Initializer.
  219. Args:
  220. name: The name, e.g. 'Pattern'.
  221. type_var: The type parameter, e.g. AnyStr, or the
  222. specific type, e.g. str.
  223. impl_type: The implementation type.
  224. type_checker: Function that takes an impl_type instance.
  225. and returns a value that should be a type_var instance.
  226. """
  227. assert isinstance(name, basestring), repr(name)
  228. assert isinstance(impl_type, type), repr(impl_type)
  229. assert not isinstance(impl_type, TypingMeta), repr(impl_type)
  230. assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
  231. self.name = name
  232. self.type_var = type_var
  233. self.impl_type = impl_type
  234. self.type_checker = type_checker
  235. def __repr__(self):
  236. return "%s[%s]" % (self.name, _type_repr(self.type_var))
  237. def __getitem__(self, parameter):
  238. if not isinstance(self.type_var, TypeVar):
  239. raise TypeError("%s cannot be further parameterized." % self)
  240. if self.type_var.__constraints__ and isinstance(parameter, type):
  241. if not issubclass(parameter, self.type_var.__constraints__):
  242. raise TypeError("%s is not a valid substitution for %s." %
  243. (parameter, self.type_var))
  244. if isinstance(parameter, TypeVar) and parameter is not self.type_var:
  245. raise TypeError("%s cannot be re-parameterized." % self)
  246. return self.__class__(self.name, parameter,
  247. self.impl_type, self.type_checker)
  248. def __eq__(self, other):
  249. if not isinstance(other, _TypeAlias):
  250. return NotImplemented
  251. return self.name == other.name and self.type_var == other.type_var
  252. def __hash__(self):
  253. return hash((self.name, self.type_var))
  254. def __instancecheck__(self, obj):
  255. if not isinstance(self.type_var, TypeVar):
  256. raise TypeError("Parameterized type aliases cannot be used "
  257. "with isinstance().")
  258. return isinstance(obj, self.impl_type)
  259. def __subclasscheck__(self, cls):
  260. if not isinstance(self.type_var, TypeVar):
  261. raise TypeError("Parameterized type aliases cannot be used "
  262. "with issubclass().")
  263. return issubclass(cls, self.impl_type)
  264. def _get_type_vars(types, tvars):
  265. for t in types:
  266. if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
  267. t._get_type_vars(tvars)
  268. def _type_vars(types):
  269. tvars = []
  270. _get_type_vars(types, tvars)
  271. return tuple(tvars)
  272. def _eval_type(t, globalns, localns):
  273. if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
  274. return t._eval_type(globalns, localns)
  275. return t
  276. def _type_check(arg, msg):
  277. """Check that the argument is a type, and return it (internal helper).
  278. As a special case, accept None and return type(None) instead.
  279. Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
  280. The msg argument is a human-readable error message, e.g.
  281. "Union[arg, ...]: arg should be a type."
  282. We append the repr() of the actual value (truncated to 100 chars).
  283. """
  284. if arg is None:
  285. return type(None)
  286. if isinstance(arg, basestring):
  287. arg = _ForwardRef(arg)
  288. if (
  289. isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
  290. not isinstance(arg, (type, _TypingBase)) and not callable(arg)
  291. ):
  292. raise TypeError(msg + " Got %.100r." % (arg,))
  293. # Bare Union etc. are not valid as type arguments
  294. if (
  295. type(arg).__name__ in ('_Union', '_Optional') and
  296. not getattr(arg, '__origin__', None) or
  297. isinstance(arg, TypingMeta) and arg._gorg in (Generic, Protocol)
  298. ):
  299. raise TypeError("Plain %s is not valid as type argument" % arg)
  300. return arg
  301. def _type_repr(obj):
  302. """Return the repr() of an object, special-casing types (internal helper).
  303. If obj is a type, we return a shorter version than the default
  304. type.__repr__, based on the module and qualified name, which is
  305. typically enough to uniquely identify a type. For everything
  306. else, we fall back on repr(obj).
  307. """
  308. if isinstance(obj, type) and not isinstance(obj, TypingMeta):
  309. if obj.__module__ == '__builtin__':
  310. return _qualname(obj)
  311. return '%s.%s' % (obj.__module__, _qualname(obj))
  312. if obj is Ellipsis:
  313. return '...'
  314. if isinstance(obj, types.FunctionType):
  315. return obj.__name__
  316. return repr(obj)
  317. class ClassVarMeta(TypingMeta):
  318. """Metaclass for _ClassVar"""
  319. def __new__(cls, name, bases, namespace):
  320. cls.assert_no_subclassing(bases)
  321. self = super(ClassVarMeta, cls).__new__(cls, name, bases, namespace)
  322. return self
  323. class _ClassVar(_FinalTypingBase):
  324. """Special type construct to mark class variables.
  325. An annotation wrapped in ClassVar indicates that a given
  326. attribute is intended to be used as a class variable and
  327. should not be set on instances of that class. Usage::
  328. class Starship:
  329. stats = {} # type: ClassVar[Dict[str, int]] # class variable
  330. damage = 10 # type: int # instance variable
  331. ClassVar accepts only types and cannot be further subscribed.
  332. Note that ClassVar is not a class itself, and should not
  333. be used with isinstance() or issubclass().
  334. """
  335. __metaclass__ = ClassVarMeta
  336. __slots__ = ('__type__',)
  337. def __init__(self, tp=None, _root=False):
  338. self.__type__ = tp
  339. def __getitem__(self, item):
  340. cls = type(self)
  341. if self.__type__ is None:
  342. return cls(_type_check(item,
  343. '{} accepts only types.'.format(cls.__name__[1:])),
  344. _root=True)
  345. raise TypeError('{} cannot be further subscripted'
  346. .format(cls.__name__[1:]))
  347. def _eval_type(self, globalns, localns):
  348. return type(self)(_eval_type(self.__type__, globalns, localns),
  349. _root=True)
  350. def __repr__(self):
  351. r = super(_ClassVar, self).__repr__()
  352. if self.__type__ is not None:
  353. r += '[{}]'.format(_type_repr(self.__type__))
  354. return r
  355. def __hash__(self):
  356. return hash((type(self).__name__, self.__type__))
  357. def __eq__(self, other):
  358. if not isinstance(other, _ClassVar):
  359. return NotImplemented
  360. if self.__type__ is not None:
  361. return self.__type__ == other.__type__
  362. return self is other
  363. ClassVar = _ClassVar(_root=True)
  364. class _FinalMeta(TypingMeta):
  365. """Metaclass for _Final"""
  366. def __new__(cls, name, bases, namespace):
  367. cls.assert_no_subclassing(bases)
  368. self = super(_FinalMeta, cls).__new__(cls, name, bases, namespace)
  369. return self
  370. class _Final(_FinalTypingBase):
  371. """A special typing construct to indicate that a name
  372. cannot be re-assigned or overridden in a subclass.
  373. For example:
  374. MAX_SIZE: Final = 9000
  375. MAX_SIZE += 1 # Error reported by type checker
  376. class Connection:
  377. TIMEOUT: Final[int] = 10
  378. class FastConnector(Connection):
  379. TIMEOUT = 1 # Error reported by type checker
  380. There is no runtime checking of these properties.
  381. """
  382. __metaclass__ = _FinalMeta
  383. __slots__ = ('__type__',)
  384. def __init__(self, tp=None, **kwds):
  385. self.__type__ = tp
  386. def __getitem__(self, item):
  387. cls = type(self)
  388. if self.__type__ is None:
  389. return cls(_type_check(item,
  390. '{} accepts only single type.'.format(cls.__name__[1:])),
  391. _root=True)
  392. raise TypeError('{} cannot be further subscripted'
  393. .format(cls.__name__[1:]))
  394. def _eval_type(self, globalns, localns):
  395. new_tp = _eval_type(self.__type__, globalns, localns)
  396. if new_tp == self.__type__:
  397. return self
  398. return type(self)(new_tp, _root=True)
  399. def __repr__(self):
  400. r = super(_Final, self).__repr__()
  401. if self.__type__ is not None:
  402. r += '[{}]'.format(_type_repr(self.__type__))
  403. return r
  404. def __hash__(self):
  405. return hash((type(self).__name__, self.__type__))
  406. def __eq__(self, other):
  407. if not isinstance(other, _Final):
  408. return NotImplemented
  409. if self.__type__ is not None:
  410. return self.__type__ == other.__type__
  411. return self is other
  412. Final = _Final(_root=True)
  413. def final(f):
  414. """This decorator can be used to indicate to type checkers that
  415. the decorated method cannot be overridden, and decorated class
  416. cannot be subclassed. For example:
  417. class Base:
  418. @final
  419. def done(self) -> None:
  420. ...
  421. class Sub(Base):
  422. def done(self) -> None: # Error reported by type checker
  423. ...
  424. @final
  425. class Leaf:
  426. ...
  427. class Other(Leaf): # Error reported by type checker
  428. ...
  429. There is no runtime checking of these properties.
  430. """
  431. return f
  432. class _LiteralMeta(TypingMeta):
  433. """Metaclass for _Literal"""
  434. def __new__(cls, name, bases, namespace):
  435. cls.assert_no_subclassing(bases)
  436. self = super(_LiteralMeta, cls).__new__(cls, name, bases, namespace)
  437. return self
  438. class _Literal(_FinalTypingBase):
  439. """A type that can be used to indicate to type checkers that the
  440. corresponding value has a value literally equivalent to the
  441. provided parameter. For example:
  442. var: Literal[4] = 4
  443. The type checker understands that 'var' is literally equal to the
  444. value 4 and no other value.
  445. Literal[...] cannot be subclassed. There is no runtime checking
  446. verifying that the parameter is actually a value instead of a type.
  447. """
  448. __metaclass__ = _LiteralMeta
  449. __slots__ = ('__values__',)
  450. def __init__(self, values=None, **kwds):
  451. self.__values__ = values
  452. def __getitem__(self, item):
  453. cls = type(self)
  454. if self.__values__ is None:
  455. if not isinstance(item, tuple):
  456. item = (item,)
  457. return cls(values=item,
  458. _root=True)
  459. raise TypeError('{} cannot be further subscripted'
  460. .format(cls.__name__[1:]))
  461. def _eval_type(self, globalns, localns):
  462. return self
  463. def __repr__(self):
  464. r = super(_Literal, self).__repr__()
  465. if self.__values__ is not None:
  466. r += '[{}]'.format(', '.join(map(_type_repr, self.__values__)))
  467. return r
  468. def __hash__(self):
  469. return hash((type(self).__name__, self.__values__))
  470. def __eq__(self, other):
  471. if not isinstance(other, _Literal):
  472. return NotImplemented
  473. if self.__values__ is not None:
  474. return self.__values__ == other.__values__
  475. return self is other
  476. Literal = _Literal(_root=True)
  477. class AnyMeta(TypingMeta):
  478. """Metaclass for Any."""
  479. def __new__(cls, name, bases, namespace):
  480. cls.assert_no_subclassing(bases)
  481. self = super(AnyMeta, cls).__new__(cls, name, bases, namespace)
  482. return self
  483. class _Any(_FinalTypingBase):
  484. """Special type indicating an unconstrained type.
  485. - Any is compatible with every type.
  486. - Any assumed to have all methods.
  487. - All values assumed to be instances of Any.
  488. Note that all the above statements are true from the point of view of
  489. static type checkers. At runtime, Any should not be used with instance
  490. or class checks.
  491. """
  492. __metaclass__ = AnyMeta
  493. __slots__ = ()
  494. def __instancecheck__(self, obj):
  495. raise TypeError("Any cannot be used with isinstance().")
  496. def __subclasscheck__(self, cls):
  497. raise TypeError("Any cannot be used with issubclass().")
  498. Any = _Any(_root=True)
  499. class NoReturnMeta(TypingMeta):
  500. """Metaclass for NoReturn."""
  501. def __new__(cls, name, bases, namespace):
  502. cls.assert_no_subclassing(bases)
  503. self = super(NoReturnMeta, cls).__new__(cls, name, bases, namespace)
  504. return self
  505. class _NoReturn(_FinalTypingBase):
  506. """Special type indicating functions that never return.
  507. Example::
  508. from typing import NoReturn
  509. def stop() -> NoReturn:
  510. raise Exception('no way')
  511. This type is invalid in other positions, e.g., ``List[NoReturn]``
  512. will fail in static type checkers.
  513. """
  514. __metaclass__ = NoReturnMeta
  515. __slots__ = ()
  516. def __instancecheck__(self, obj):
  517. raise TypeError("NoReturn cannot be used with isinstance().")
  518. def __subclasscheck__(self, cls):
  519. raise TypeError("NoReturn cannot be used with issubclass().")
  520. NoReturn = _NoReturn(_root=True)
  521. class TypeVarMeta(TypingMeta):
  522. def __new__(cls, name, bases, namespace):
  523. cls.assert_no_subclassing(bases)
  524. return super(TypeVarMeta, cls).__new__(cls, name, bases, namespace)
  525. class TypeVar(_TypingBase):
  526. """Type variable.
  527. Usage::
  528. T = TypeVar('T') # Can be anything
  529. A = TypeVar('A', str, bytes) # Must be str or bytes
  530. Type variables exist primarily for the benefit of static type
  531. checkers. They serve as the parameters for generic types as well
  532. as for generic function definitions. See class Generic for more
  533. information on generic types. Generic functions work as follows:
  534. def repeat(x: T, n: int) -> List[T]:
  535. '''Return a list containing n references to x.'''
  536. return [x]*n
  537. def longest(x: A, y: A) -> A:
  538. '''Return the longest of two strings.'''
  539. return x if len(x) >= len(y) else y
  540. The latter example's signature is essentially the overloading
  541. of (str, str) -> str and (bytes, bytes) -> bytes. Also note
  542. that if the arguments are instances of some subclass of str,
  543. the return type is still plain str.
  544. At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
  545. Type variables defined with covariant=True or contravariant=True
  546. can be used do declare covariant or contravariant generic types.
  547. See PEP 484 for more details. By default generic types are invariant
  548. in all type variables.
  549. Type variables can be introspected. e.g.:
  550. T.__name__ == 'T'
  551. T.__constraints__ == ()
  552. T.__covariant__ == False
  553. T.__contravariant__ = False
  554. A.__constraints__ == (str, bytes)
  555. """
  556. __metaclass__ = TypeVarMeta
  557. __slots__ = ('__name__', '__bound__', '__constraints__',
  558. '__covariant__', '__contravariant__')
  559. def __init__(self, name, *constraints, **kwargs):
  560. super(TypeVar, self).__init__(name, *constraints, **kwargs)
  561. bound = kwargs.get('bound', None)
  562. covariant = kwargs.get('covariant', False)
  563. contravariant = kwargs.get('contravariant', False)
  564. self.__name__ = name
  565. if covariant and contravariant:
  566. raise ValueError("Bivariant types are not supported.")
  567. self.__covariant__ = bool(covariant)
  568. self.__contravariant__ = bool(contravariant)
  569. if constraints and bound is not None:
  570. raise TypeError("Constraints cannot be combined with bound=...")
  571. if constraints and len(constraints) == 1:
  572. raise TypeError("A single constraint is not allowed")
  573. msg = "TypeVar(name, constraint, ...): constraints must be types."
  574. self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
  575. if bound:
  576. self.__bound__ = _type_check(bound, "Bound must be a type.")
  577. else:
  578. self.__bound__ = None
  579. def _get_type_vars(self, tvars):
  580. if self not in tvars:
  581. tvars.append(self)
  582. def __repr__(self):
  583. if self.__covariant__:
  584. prefix = '+'
  585. elif self.__contravariant__:
  586. prefix = '-'
  587. else:
  588. prefix = '~'
  589. return prefix + self.__name__
  590. def __instancecheck__(self, instance):
  591. raise TypeError("Type variables cannot be used with isinstance().")
  592. def __subclasscheck__(self, cls):
  593. raise TypeError("Type variables cannot be used with issubclass().")
  594. # Some unconstrained type variables. These are used by the container types.
  595. # (These are not for export.)
  596. T = TypeVar('T') # Any type.
  597. KT = TypeVar('KT') # Key type.
  598. VT = TypeVar('VT') # Value type.
  599. T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
  600. V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
  601. VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
  602. T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
  603. # A useful type variable with constraints. This represents string types.
  604. # (This one *is* for export!)
  605. AnyStr = TypeVar('AnyStr', bytes, unicode)
  606. def _replace_arg(arg, tvars, args):
  607. """An internal helper function: replace arg if it is a type variable
  608. found in tvars with corresponding substitution from args or
  609. with corresponding substitution sub-tree if arg is a generic type.
  610. """
  611. if tvars is None:
  612. tvars = []
  613. if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)):
  614. return arg._subs_tree(tvars, args)
  615. if isinstance(arg, TypeVar):
  616. for i, tvar in enumerate(tvars):
  617. if arg == tvar:
  618. return args[i]
  619. return arg
  620. # Special typing constructs Union, Optional, Generic, Callable and Tuple
  621. # use three special attributes for internal bookkeeping of generic types:
  622. # * __parameters__ is a tuple of unique free type parameters of a generic
  623. # type, for example, Dict[T, T].__parameters__ == (T,);
  624. # * __origin__ keeps a reference to a type that was subscripted,
  625. # e.g., Union[T, int].__origin__ == Union;
  626. # * __args__ is a tuple of all arguments used in subscripting,
  627. # e.g., Dict[T, int].__args__ == (T, int).
  628. def _subs_tree(cls, tvars=None, args=None):
  629. """An internal helper function: calculate substitution tree
  630. for generic cls after replacing its type parameters with
  631. substitutions in tvars -> args (if any).
  632. Repeat the same following __origin__'s.
  633. Return a list of arguments with all possible substitutions
  634. performed. Arguments that are generic classes themselves are represented
  635. as tuples (so that no new classes are created by this function).
  636. For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
  637. """
  638. if cls.__origin__ is None:
  639. return cls
  640. # Make of chain of origins (i.e. cls -> cls.__origin__)
  641. current = cls.__origin__
  642. orig_chain = []
  643. while current.__origin__ is not None:
  644. orig_chain.append(current)
  645. current = current.__origin__
  646. # Replace type variables in __args__ if asked ...
  647. tree_args = []
  648. for arg in cls.__args__:
  649. tree_args.append(_replace_arg(arg, tvars, args))
  650. # ... then continue replacing down the origin chain.
  651. for ocls in orig_chain:
  652. new_tree_args = []
  653. for arg in ocls.__args__:
  654. new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
  655. tree_args = new_tree_args
  656. return tree_args
  657. def _remove_dups_flatten(parameters):
  658. """An internal helper for Union creation and substitution: flatten Union's
  659. among parameters, then remove duplicates and strict subclasses.
  660. """
  661. # Flatten out Union[Union[...], ...].
  662. params = []
  663. for p in parameters:
  664. if isinstance(p, _Union) and p.__origin__ is Union:
  665. params.extend(p.__args__)
  666. elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
  667. params.extend(p[1:])
  668. else:
  669. params.append(p)
  670. # Weed out strict duplicates, preserving the first of each occurrence.
  671. all_params = set(params)
  672. if len(all_params) < len(params):
  673. new_params = []
  674. for t in params:
  675. if t in all_params:
  676. new_params.append(t)
  677. all_params.remove(t)
  678. params = new_params
  679. assert not all_params, all_params
  680. # Weed out subclasses.
  681. # E.g. Union[int, Employee, Manager] == Union[int, Employee].
  682. # If object is present it will be sole survivor among proper classes.
  683. # Never discard type variables.
  684. # (In particular, Union[str, AnyStr] != AnyStr.)
  685. all_params = set(params)
  686. for t1 in params:
  687. if not isinstance(t1, type):
  688. continue
  689. if any(isinstance(t2, type) and issubclass(t1, t2)
  690. for t2 in all_params - {t1}
  691. if not (isinstance(t2, GenericMeta) and
  692. t2.__origin__ is not None)):
  693. all_params.remove(t1)
  694. return tuple(t for t in params if t in all_params)
  695. def _check_generic(cls, parameters):
  696. # Check correct count for parameters of a generic cls (internal helper).
  697. if not cls.__parameters__:
  698. raise TypeError("%s is not a generic class" % repr(cls))
  699. alen = len(parameters)
  700. elen = len(cls.__parameters__)
  701. if alen != elen:
  702. raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
  703. ("many" if alen > elen else "few", repr(cls), alen, elen))
  704. _cleanups = []
  705. def _tp_cache(func):
  706. maxsize = 128
  707. cache = {}
  708. _cleanups.append(cache.clear)
  709. @functools.wraps(func)
  710. def inner(*args):
  711. key = args
  712. try:
  713. return cache[key]
  714. except TypeError:
  715. # Assume it's an unhashable argument.
  716. return func(*args)
  717. except KeyError:
  718. value = func(*args)
  719. if len(cache) >= maxsize:
  720. # If the cache grows too much, just start over.
  721. cache.clear()
  722. cache[key] = value
  723. return value
  724. return inner
  725. class UnionMeta(TypingMeta):
  726. """Metaclass for Union."""
  727. def __new__(cls, name, bases, namespace):
  728. cls.assert_no_subclassing(bases)
  729. return super(UnionMeta, cls).__new__(cls, name, bases, namespace)
  730. class _Union(_FinalTypingBase):
  731. """Union type; Union[X, Y] means either X or Y.
  732. To define a union, use e.g. Union[int, str]. Details:
  733. - The arguments must be types and there must be at least one.
  734. - None as an argument is a special case and is replaced by
  735. type(None).
  736. - Unions of unions are flattened, e.g.::
  737. Union[Union[int, str], float] == Union[int, str, float]
  738. - Unions of a single argument vanish, e.g.::
  739. Union[int] == int # The constructor actually returns int
  740. - Redundant arguments are skipped, e.g.::
  741. Union[int, str, int] == Union[int, str]
  742. - When comparing unions, the argument order is ignored, e.g.::
  743. Union[int, str] == Union[str, int]
  744. - When two arguments have a subclass relationship, the least
  745. derived argument is kept, e.g.::
  746. class Employee: pass
  747. class Manager(Employee): pass
  748. Union[int, Employee, Manager] == Union[int, Employee]
  749. Union[Manager, int, Employee] == Union[int, Employee]
  750. Union[Employee, Manager] == Employee
  751. - Similar for object::
  752. Union[int, object] == object
  753. - You cannot subclass or instantiate a union.
  754. - You can use Optional[X] as a shorthand for Union[X, None].
  755. """
  756. __metaclass__ = UnionMeta
  757. __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__')
  758. def __new__(cls, parameters=None, origin=None, *args, **kwds):
  759. self = super(_Union, cls).__new__(cls, parameters, origin, *args, **kwds)
  760. if origin is None:
  761. self.__parameters__ = None
  762. self.__args__ = None
  763. self.__origin__ = None
  764. self.__tree_hash__ = hash(frozenset(('Union',)))
  765. return self
  766. if not isinstance(parameters, tuple):
  767. raise TypeError("Expected parameters=<tuple>")
  768. if origin is Union:
  769. parameters = _remove_dups_flatten(parameters)
  770. # It's not a union if there's only one type left.
  771. if len(parameters) == 1:
  772. return parameters[0]
  773. self.__parameters__ = _type_vars(parameters)
  774. self.__args__ = parameters
  775. self.__origin__ = origin
  776. # Pre-calculate the __hash__ on instantiation.
  777. # This improves speed for complex substitutions.
  778. subs_tree = self._subs_tree()
  779. if isinstance(subs_tree, tuple):
  780. self.__tree_hash__ = hash(frozenset(subs_tree))
  781. else:
  782. self.__tree_hash__ = hash(subs_tree)
  783. return self
  784. def _eval_type(self, globalns, localns):
  785. if self.__args__ is None:
  786. return self
  787. ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__)
  788. ev_origin = _eval_type(self.__origin__, globalns, localns)
  789. if ev_args == self.__args__ and ev_origin == self.__origin__:
  790. # Everything is already evaluated.
  791. return self
  792. return self.__class__(ev_args, ev_origin, _root=True)
  793. def _get_type_vars(self, tvars):
  794. if self.__origin__ and self.__parameters__:
  795. _get_type_vars(self.__parameters__, tvars)
  796. def __repr__(self):
  797. if self.__origin__ is None:
  798. return super(_Union, self).__repr__()
  799. tree = self._subs_tree()
  800. if not isinstance(tree, tuple):
  801. return repr(tree)
  802. return tree[0]._tree_repr(tree)
  803. def _tree_repr(self, tree):
  804. arg_list = []
  805. for arg in tree[1:]:
  806. if not isinstance(arg, tuple):
  807. arg_list.append(_type_repr(arg))
  808. else:
  809. arg_list.append(arg[0]._tree_repr(arg))
  810. return super(_Union, self).__repr__() + '[%s]' % ', '.join(arg_list)
  811. @_tp_cache
  812. def __getitem__(self, parameters):
  813. if parameters == ():
  814. raise TypeError("Cannot take a Union of no types.")
  815. if not isinstance(parameters, tuple):
  816. parameters = (parameters,)
  817. if self.__origin__ is None:
  818. msg = "Union[arg, ...]: each arg must be a type."
  819. else:
  820. msg = "Parameters to generic types must be types."
  821. parameters = tuple(_type_check(p, msg) for p in parameters)
  822. if self is not Union:
  823. _check_generic(self, parameters)
  824. return self.__class__(parameters, origin=self, _root=True)
  825. def _subs_tree(self, tvars=None, args=None):
  826. if self is Union:
  827. return Union # Nothing to substitute
  828. tree_args = _subs_tree(self, tvars, args)
  829. tree_args = _remove_dups_flatten(tree_args)
  830. if len(tree_args) == 1:
  831. return tree_args[0] # Union of a single type is that type
  832. return (Union,) + tree_args
  833. def __eq__(self, other):
  834. if isinstance(other, _Union):
  835. return self.__tree_hash__ == other.__tree_hash__
  836. elif self is not Union:
  837. return self._subs_tree() == other
  838. else:
  839. return self is other
  840. def __hash__(self):
  841. return self.__tree_hash__
  842. def __instancecheck__(self, obj):
  843. raise TypeError("Unions cannot be used with isinstance().")
  844. def __subclasscheck__(self, cls):
  845. raise TypeError("Unions cannot be used with issubclass().")
  846. Union = _Union(_root=True)
  847. class OptionalMeta(TypingMeta):
  848. """Metaclass for Optional."""
  849. def __new__(cls, name, bases, namespace):
  850. cls.assert_no_subclassing(bases)
  851. return super(OptionalMeta, cls).__new__(cls, name, bases, namespace)
  852. class _Optional(_FinalTypingBase):
  853. """Optional type.
  854. Optional[X] is equivalent to Union[X, None].
  855. """
  856. __metaclass__ = OptionalMeta
  857. __slots__ = ()
  858. @_tp_cache
  859. def __getitem__(self, arg):
  860. arg = _type_check(arg, "Optional[t] requires a single type.")
  861. return Union[arg, type(None)]
  862. Optional = _Optional(_root=True)
  863. def _next_in_mro(cls):
  864. """Helper for Generic.__new__.
  865. Returns the class after the last occurrence of Generic or
  866. Generic[...] in cls.__mro__.
  867. """
  868. next_in_mro = object
  869. # Look for the last occurrence of Generic or Generic[...].
  870. for i, c in enumerate(cls.__mro__[:-1]):
  871. if isinstance(c, GenericMeta) and c._gorg is Generic:
  872. next_in_mro = cls.__mro__[i + 1]
  873. return next_in_mro
  874. def _make_subclasshook(cls):
  875. """Construct a __subclasshook__ callable that incorporates
  876. the associated __extra__ class in subclass checks performed
  877. against cls.
  878. """
  879. if isinstance(cls.__extra__, abc.ABCMeta):
  880. # The logic mirrors that of ABCMeta.__subclasscheck__.
  881. # Registered classes need not be checked here because
  882. # cls and its extra share the same _abc_registry.
  883. def __extrahook__(cls, subclass):
  884. res = cls.__extra__.__subclasshook__(subclass)
  885. if res is not NotImplemented:
  886. return res
  887. if cls.__extra__ in getattr(subclass, '__mro__', ()):
  888. return True
  889. for scls in cls.__extra__.__subclasses__():
  890. if isinstance(scls, GenericMeta):
  891. continue
  892. if issubclass(subclass, scls):
  893. return True
  894. return NotImplemented
  895. else:
  896. # For non-ABC extras we'll just call issubclass().
  897. def __extrahook__(cls, subclass):
  898. if cls.__extra__ and issubclass(subclass, cls.__extra__):
  899. return True
  900. return NotImplemented
  901. return classmethod(__extrahook__)
  902. class GenericMeta(TypingMeta, abc.ABCMeta):
  903. """Metaclass for generic types.
  904. This is a metaclass for typing.Generic and generic ABCs defined in
  905. typing module. User defined subclasses of GenericMeta can override
  906. __new__ and invoke super().__new__. Note that GenericMeta.__new__
  907. has strict rules on what is allowed in its bases argument:
  908. * plain Generic is disallowed in bases;
  909. * Generic[...] should appear in bases at most once;
  910. * if Generic[...] is present, then it should list all type variables
  911. that appear in other bases.
  912. In addition, type of all generic bases is erased, e.g., C[int] is
  913. stripped to plain C.
  914. """
  915. def __new__(cls, name, bases, namespace,
  916. tvars=None, args=None, origin=None, extra=None, orig_bases=None):
  917. """Create a new generic class. GenericMeta.__new__ accepts
  918. keyword arguments that are used for internal bookkeeping, therefore
  919. an override should pass unused keyword arguments to super().
  920. """
  921. if tvars is not None:
  922. # Called from __getitem__() below.
  923. assert origin is not None
  924. assert all(isinstance(t, TypeVar) for t in tvars), tvars
  925. else:
  926. # Called from class statement.
  927. assert tvars is None, tvars
  928. assert args is None, args
  929. assert origin is None, origin
  930. # Get the full set of tvars from the bases.
  931. tvars = _type_vars(bases)
  932. # Look for Generic[T1, ..., Tn].
  933. # If found, tvars must be a subset of it.
  934. # If not found, tvars is it.
  935. # Also check for and reject plain Generic,
  936. # and reject multiple Generic[...].
  937. gvars = None
  938. for base in bases:
  939. if base is Generic:
  940. raise TypeError("Cannot inherit from plain Generic")
  941. if (isinstance(base, GenericMeta) and
  942. base.__origin__ in (Generic, Protocol)):
  943. if gvars is not None:
  944. raise TypeError(
  945. "Cannot inherit from Generic[...] or"
  946. " Protocol[...] multiple times.")
  947. gvars = base.__parameters__
  948. if gvars is None:
  949. gvars = tvars
  950. else:
  951. tvarset = set(tvars)
  952. gvarset = set(gvars)
  953. if not tvarset <= gvarset:
  954. raise TypeError(
  955. "Some type variables (%s) "
  956. "are not listed in %s[%s]" %
  957. (", ".join(str(t) for t in tvars if t not in gvarset),
  958. "Generic" if any(b.__origin__ is Generic
  959. for b in bases) else "Protocol",
  960. ", ".join(str(g) for g in gvars)))
  961. tvars = gvars
  962. initial_bases = bases
  963. if extra is None:
  964. extra = namespace.get('__extra__')
  965. if extra is not None and type(extra) is abc.ABCMeta and extra not in bases:
  966. bases = (extra,) + bases
  967. bases = tuple(b._gorg if isinstance(b, GenericMeta) else b for b in bases)
  968. # remove bare Generic from bases if there are other generic bases
  969. if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
  970. bases = tuple(b for b in bases if b is not Generic)
  971. namespace.update({'__origin__': origin, '__extra__': extra})
  972. self = super(GenericMeta, cls).__new__(cls, name, bases, namespace)
  973. super(GenericMeta, self).__setattr__('_gorg',
  974. self if not origin else origin._gorg)
  975. self.__parameters__ = tvars
  976. # Be prepared that GenericMeta will be subclassed by TupleMeta
  977. # and CallableMeta, those two allow ..., (), or [] in __args___.
  978. self.__args__ = tuple(Ellipsis if a is _TypingEllipsis else
  979. () if a is _TypingEmpty else
  980. a for a in args) if args else None
  981. # Speed hack (https://github.com/python/typing/issues/196).
  982. self.__next_in_mro__ = _next_in_mro(self)
  983. # Preserve base classes on subclassing (__bases__ are type erased now).
  984. if orig_bases is None:
  985. self.__orig_bases__ = initial_bases
  986. # This allows unparameterized generic collections to be used
  987. # with issubclass() and isinstance() in the same way as their
  988. # collections.abc counterparts (e.g., isinstance([], Iterable)).
  989. if (
  990. '__subclasshook__' not in namespace and extra or
  991. # allow overriding
  992. getattr(self.__subclasshook__, '__name__', '') == '__extrahook__'
  993. ):
  994. self.__subclasshook__ = _make_subclasshook(self)
  995. if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2.
  996. self.__qualname__ = origin.__qualname__
  997. self.__tree_hash__ = (hash(self._subs_tree()) if origin else
  998. super(GenericMeta, self).__hash__())
  999. return self
  1000. def __init__(self, *args, **kwargs):
  1001. super(GenericMeta, self).__init__(*args, **kwargs)
  1002. if isinstance(self.__extra__, abc.ABCMeta):
  1003. self._abc_registry = self.__extra__._abc_registry
  1004. self._abc_cache = self.__extra__._abc_cache
  1005. elif self.__origin__ is not None:
  1006. self._abc_registry = self.__origin__._abc_registry
  1007. self._abc_cache = self.__origin__._abc_cache
  1008. # _abc_negative_cache and _abc_negative_cache_version
  1009. # realised as descriptors, since GenClass[t1, t2, ...] always
  1010. # share subclass info with GenClass.
  1011. # This is an important memory optimization.
  1012. @property
  1013. def _abc_negative_cache(self):
  1014. if isinstance(self.__extra__, abc.ABCMeta):
  1015. return self.__extra__._abc_negative_cache
  1016. return self._gorg._abc_generic_negative_cache
  1017. @_abc_negative_cache.setter
  1018. def _abc_negative_cache(self, value):
  1019. if self.__origin__ is None:
  1020. if isinstance(self.__extra__, abc.ABCMeta):
  1021. self.__extra__._abc_negative_cache = value
  1022. else:
  1023. self._abc_generic_negative_cache = value
  1024. @property
  1025. def _abc_negative_cache_version(self):
  1026. if isinstance(self.__extra__, abc.ABCMeta):
  1027. return self.__extra__._abc_negative_cache_version
  1028. return self._gorg._abc_generic_negative_cache_version
  1029. @_abc_negative_cache_version.setter
  1030. def _abc_negative_cache_version(self, value):
  1031. if self.__origin__ is None:
  1032. if isinstance(self.__extra__, abc.ABCMeta):
  1033. self.__extra__._abc_negative_cache_version = value
  1034. else:
  1035. self._abc_generic_negative_cache_version = value
  1036. def _get_type_vars(self, tvars):
  1037. if self.__origin__ and self.__parameters__:
  1038. _get_type_vars(self.__parameters__, tvars)
  1039. def _eval_type(self, globalns, localns):
  1040. ev_origin = (self.__origin__._eval_type(globalns, localns)
  1041. if self.__origin__ else None)
  1042. ev_args = tuple(_eval_type(a, globalns, localns) for a
  1043. in self.__args__) if self.__args__ else None
  1044. if ev_origin == self.__origin__ and ev_args == self.__args__:
  1045. return self
  1046. return self.__class__(self.__name__,
  1047. self.__bases__,
  1048. dict(self.__dict__),
  1049. tvars=_type_vars(ev_args) if ev_args else None,
  1050. args=ev_args,
  1051. origin=ev_origin,
  1052. extra=self.__extra__,
  1053. orig_bases=self.__orig_bases__)
  1054. def __repr__(self):
  1055. if self.__origin__ is None:
  1056. return super(GenericMeta, self).__repr__()
  1057. return self._tree_repr(self._subs_tree())
  1058. def _tree_repr(self, tree):
  1059. arg_list = []
  1060. for arg in tree[1:]:
  1061. if arg == ():
  1062. arg_list.append('()')
  1063. elif not isinstance(arg, tuple):
  1064. arg_list.append(_type_repr(arg))
  1065. else:
  1066. arg_list.append(arg[0]._tree_repr(arg))
  1067. return super(GenericMeta, self).__repr__() + '[%s]' % ', '.join(arg_list)
  1068. def _subs_tree(self, tvars=None, args=None):
  1069. if self.__origin__ is None:
  1070. return self
  1071. tree_args = _subs_tree(self, tvars, args)
  1072. return (self._gorg,) + tuple(tree_args)
  1073. def __eq__(self, other):
  1074. if not isinstance(other, GenericMeta):
  1075. return NotImplemented
  1076. if self.__origin__ is None or other.__origin__ is None:
  1077. return self is other
  1078. return self.__tree_hash__ == other.__tree_hash__
  1079. def __hash__(self):
  1080. return self.__tree_hash__
  1081. @_tp_cache
  1082. def __getitem__(self, params):
  1083. if not isinstance(params, tuple):
  1084. params = (params,)
  1085. if not params and self._gorg is not Tuple:
  1086. raise TypeError(
  1087. "Parameter list to %s[...] cannot be empty" % _qualname(self))
  1088. msg = "Parameters to generic types must be types."
  1089. params = tuple(_type_check(p, msg) for p in params)
  1090. if self in (Generic, Protocol):
  1091. # Generic can only be subscripted with unique type variables.
  1092. if not all(isinstance(p, TypeVar) for p in params):
  1093. raise TypeError(
  1094. "Parameters to %s[...] must all be type variables" % self.__name__)
  1095. if len(set(params)) != len(params):
  1096. raise TypeError(
  1097. "Parameters to %s[...] must all be unique" % self.__name__)
  1098. tvars = params
  1099. args = params
  1100. elif self in (Tuple, Callable):
  1101. tvars = _type_vars(params)
  1102. args = params
  1103. elif self.__origin__ in (Generic, Protocol):
  1104. # Can't subscript Generic[...] or Protocol[...].
  1105. raise TypeError("Cannot subscript already-subscripted %s" %
  1106. repr(self))
  1107. else:
  1108. # Subscripting a regular Generic subclass.
  1109. _check_generic(self, params)
  1110. tvars = _type_vars(params)
  1111. args = params
  1112. prepend = (self,) if self.__origin__ is None else ()
  1113. return self.__class__(self.__name__,
  1114. prepend + self.__bases__,
  1115. dict(self.__dict__),
  1116. tvars=tvars,
  1117. args=args,
  1118. origin=self,
  1119. extra=self.__extra__,
  1120. orig_bases=self.__orig_bases__)
  1121. def __subclasscheck__(self, cls):
  1122. if self.__origin__ is not None:
  1123. # These should only be modules within the standard library.
  1124. # singledispatch is an exception, because it's a Python 2 backport
  1125. # of functools.singledispatch.
  1126. whitelist = ['abc', 'functools', 'singledispatch']
  1127. if (sys._getframe(1).f_globals['__name__'] in whitelist or
  1128. # The second frame is needed for the case where we came
  1129. # from _ProtocolMeta.__subclasscheck__.
  1130. sys._getframe(2).f_globals['__name__'] in whitelist):
  1131. return False
  1132. raise TypeError("Parameterized generics cannot be used with class "
  1133. "or instance checks")
  1134. if self is Generic:
  1135. raise TypeError("Class %r cannot be used with class "
  1136. "or instance checks" % self)
  1137. return super(GenericMeta, self).__subclasscheck__(cls)
  1138. def __instancecheck__(self, instance):
  1139. # Since we extend ABC.__subclasscheck__ and
  1140. # ABC.__instancecheck__ inlines the cache checking done by the
  1141. # latter, we must extend __instancecheck__ too. For simplicity
  1142. # we just skip the cache check -- instance checks for generic
  1143. # classes are supposed to be rare anyways.
  1144. if hasattr(instance, "__class__"):
  1145. return issubclass(instance.__class__, self)
  1146. return False
  1147. def __setattr__(self, attr, value):
  1148. # We consider all the subscripted genrics as proxies for original class
  1149. if (
  1150. attr.startswith('__') and attr.endswith('__') or
  1151. attr.startswith('_abc_')
  1152. ):
  1153. super(GenericMeta, self).__setattr__(attr, value)
  1154. else:
  1155. super(GenericMeta, self._gorg).__setattr__(attr, value)
  1156. def _copy_generic(self):
  1157. """Hack to work around https://bugs.python.org/issue11480 on Python 2"""
  1158. return self.__class__(self.__name__, self.__bases__, dict(self.__dict__),
  1159. self.__parameters__, self.__args__, self.__origin__,
  1160. self.__extra__, self.__orig_bases__)
  1161. copy._copy_dispatch[GenericMeta] = _copy_generic
  1162. # Prevent checks for Generic to crash when defining Generic.
  1163. Generic = None
  1164. def _generic_new(base_cls, cls, *args, **kwds):
  1165. # Assure type is erased on instantiation,
  1166. # but attempt to store it in __orig_class__
  1167. if cls.__origin__ is None:
  1168. if (base_cls.__new__ is object.__new__ and
  1169. cls.__init__ is not object.__init__):
  1170. return base_cls.__new__(cls)
  1171. else:
  1172. return base_cls.__new__(cls, *args, **kwds)
  1173. else:
  1174. origin = cls._gorg
  1175. if (base_cls.__new__ is object.__new__ and
  1176. cls.__init__ is not object.__init__):
  1177. obj = base_cls.__new__(origin)
  1178. else:
  1179. obj = base_cls.__new__(origin, *args, **kwds)
  1180. try:
  1181. obj.__orig_class__ = cls
  1182. except AttributeError:
  1183. pass
  1184. obj.__init__(*args, **kwds)
  1185. return obj
  1186. class Generic(object):
  1187. """Abstract base class for generic types.
  1188. A generic type is typically declared by inheriting from
  1189. this class parameterized with one or more type variables.
  1190. For example, a generic mapping type might be defined as::
  1191. class Mapping(Generic[KT, VT]):
  1192. def __getitem__(self, key: KT) -> VT:
  1193. ...
  1194. # Etc.
  1195. This class can then be used as follows::
  1196. def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
  1197. try:
  1198. return mapping[key]
  1199. except KeyError:
  1200. return default
  1201. """
  1202. __metaclass__ = GenericMeta
  1203. __slots__ = ()
  1204. def __new__(cls, *args, **kwds):
  1205. if cls._gorg is Generic:
  1206. raise TypeError("Type Generic cannot be instantiated; "
  1207. "it can be used only as a base class")
  1208. return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
  1209. class _TypingEmpty(object):
  1210. """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
  1211. to allow empty list/tuple in specific places, without allowing them
  1212. to sneak in where prohibited.
  1213. """
  1214. class _TypingEllipsis(object):
  1215. """Internal placeholder for ... (ellipsis)."""
  1216. class TupleMeta(GenericMeta):
  1217. """Metaclass for Tuple (internal)."""
  1218. @_tp_cache
  1219. def __getitem__(self, parameters):
  1220. if self.__origin__ is not None or self._gorg is not Tuple:
  1221. # Normal generic rules apply if this is not the first subscription
  1222. # or a subscription of a subclass.
  1223. return super(TupleMeta, self).__getitem__(parameters)
  1224. if parameters == ():
  1225. return super(TupleMeta, self).__getitem__((_TypingEmpty,))
  1226. if not isinstance(parameters, tuple):
  1227. parameters = (parameters,)
  1228. if len(parameters) == 2 and parameters[1] is Ellipsis:
  1229. msg = "Tuple[t, ...]: t must be a type."
  1230. p = _type_check(parameters[0], msg)
  1231. return super(TupleMeta, self).__getitem__((p, _TypingEllipsis))
  1232. msg = "Tuple[t0, t1, ...]: each t must be a type."
  1233. parameters = tuple(_type_check(p, msg) for p in parameters)
  1234. return super(TupleMeta, self).__getitem__(parameters)
  1235. def __instancecheck__(self, obj):
  1236. if self.__args__ is None:
  1237. return isinstance(obj, tuple)
  1238. raise TypeError("Parameterized Tuple cannot be used "
  1239. "with isinstance().")
  1240. def __subclasscheck__(self, cls):
  1241. if self.__args__ is None:
  1242. return issubclass(cls, tuple)
  1243. raise TypeError("Parameterized Tuple cannot be used "
  1244. "with issubclass().")
  1245. copy._copy_dispatch[TupleMeta] = _copy_generic
  1246. class Tuple(tuple):
  1247. """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
  1248. Example: Tuple[T1, T2] is a tuple of two elements corresponding
  1249. to type variables T1 and T2. Tuple[int, float, str] is a tuple
  1250. of an int, a float and a string.
  1251. To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
  1252. """
  1253. __metaclass__ = TupleMeta
  1254. __extra__ = tuple
  1255. __slots__ = ()
  1256. def __new__(cls, *args, **kwds):
  1257. if cls._gorg is Tuple:
  1258. raise TypeError("Type Tuple cannot be instantiated; "
  1259. "use tuple() instead")
  1260. return _generic_new(tuple, cls, *args, **kwds)
  1261. class CallableMeta(GenericMeta):
  1262. """ Metaclass for Callable."""
  1263. def __repr__(self):
  1264. if self.__origin__ is None:
  1265. return super(CallableMeta, self).__repr__()
  1266. return self._tree_repr(self._subs_tree())
  1267. def _tree_repr(self, tree):
  1268. if self._gorg is not Callable:
  1269. return super(CallableMeta, self)._tree_repr(tree)
  1270. # For actual Callable (not its subclass) we override
  1271. # super(CallableMeta, self)._tree_repr() for nice formatting.
  1272. arg_list = []
  1273. for arg in tree[1:]:
  1274. if not isinstance(arg, tuple):
  1275. arg_list.append(_type_repr(arg))
  1276. else:
  1277. arg_list.append(arg[0]._tree_repr(arg))
  1278. if arg_list[0] == '...':
  1279. return repr(tree[0]) + '[..., %s]' % arg_list[1]
  1280. return (repr(tree[0]) +
  1281. '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
  1282. def __getitem__(self, parameters):
  1283. """A thin wrapper around __getitem_inner__ to provide the latter
  1284. with hashable arguments to improve speed.
  1285. """
  1286. if self.__origin__ is not None or self._gorg is not Callable:
  1287. return super(CallableMeta, self).__getitem__(parameters)
  1288. if not isinstance(parameters, tuple) or len(parameters) != 2:
  1289. raise TypeError("Callable must be used as "
  1290. "Callable[[arg, ...], result].")
  1291. args, result = parameters
  1292. if args is Ellipsis:
  1293. parameters = (Ellipsis, result)
  1294. else:
  1295. if not isinstance(args, list):
  1296. raise TypeError("Callable[args, result]: args must be a list."
  1297. " Got %.100r." % (args,))
  1298. parameters = (tuple(args), result)
  1299. return self.__getitem_inner__(parameters)
  1300. @_tp_cache
  1301. def __getitem_inner__(self, parameters):
  1302. args, result = parameters
  1303. msg = "Callable[args, result]: result must be a type."
  1304. result = _type_check(result, msg)
  1305. if args is Ellipsis:
  1306. return super(CallableMeta, self).__getitem__((_TypingEllipsis, result))
  1307. msg = "Callable[[arg, ...], result]: each arg must be a type."
  1308. args = tuple(_type_check(arg, msg) for arg in args)
  1309. parameters = args + (result,)
  1310. return super(CallableMeta, self).__getitem__(parameters)
  1311. copy._copy_dispatch[CallableMeta] = _copy_generic
  1312. class Callable(object):
  1313. """Callable type; Callable[[int], str] is a function of (int) -> str.
  1314. The subscription syntax must always be used with exactly two
  1315. values: the argument list and the return type. The argument list
  1316. must be a list of types or ellipsis; the return type must be a single type.
  1317. There is no syntax to indicate optional or keyword arguments,
  1318. such function types are rarely used as callback types.
  1319. """
  1320. __metaclass__ = CallableMeta
  1321. __extra__ = collections_abc.Callable
  1322. __slots__ = ()
  1323. def __new__(cls, *args, **kwds):
  1324. if cls._gorg is Callable:
  1325. raise TypeError("Type Callable cannot be instantiated; "
  1326. "use a non-abstract subclass instead")
  1327. return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
  1328. def cast(typ, val):
  1329. """Cast a value to a type.
  1330. This returns the value unchanged. To the type checker this
  1331. signals that the return value has the designated type, but at
  1332. runtime we intentionally don't check anything (we want this
  1333. to be as fast as possible).
  1334. """
  1335. return val
  1336. def _get_defaults(func):
  1337. """Internal helper to extract the default arguments, by name."""
  1338. code = func.__code__
  1339. pos_count = code.co_argcount
  1340. arg_names = code.co_varnames
  1341. arg_names = arg_names[:pos_count]
  1342. defaults = func.__defaults__ or ()
  1343. kwdefaults = func.__kwdefaults__
  1344. res = dict(kwdefaults) if kwdefaults else {}
  1345. pos_offset = pos_count - len(defaults)
  1346. for name, value in zip(arg_names[pos_offset:], defaults):
  1347. assert name not in res
  1348. res[name] = value
  1349. return res
  1350. def get_type_hints(obj, globalns=None, localns=None):
  1351. """In Python 2 this is not supported and always returns None."""
  1352. return None
  1353. def no_type_check(arg):
  1354. """Decorator to indicate that annotations are not type hints.
  1355. The argument must be a class or function; if it is a class, it
  1356. applies recursively to all methods and classes defined in that class
  1357. (but not to methods defined in its superclasses or subclasses).
  1358. This mutates the function(s) or class(es) in place.
  1359. """
  1360. if isinstance(arg, type):
  1361. arg_attrs = arg.__dict__.copy()
  1362. for attr, val in arg.__dict__.items():
  1363. if val in arg.__bases__ + (arg,):
  1364. arg_attrs.pop(attr)
  1365. for obj in arg_attrs.values():
  1366. if isinstance(obj, types.FunctionType):
  1367. obj.__no_type_check__ = True
  1368. if isinstance(obj, type):
  1369. no_type_check(obj)
  1370. try:
  1371. arg.__no_type_check__ = True
  1372. except TypeError: # built-in classes
  1373. pass
  1374. return arg
  1375. def no_type_check_decorator(decorator):
  1376. """Decorator to give another decorator the @no_type_check effect.
  1377. This wraps the decorator with something that wraps the decorated
  1378. function in @no_type_check.
  1379. """
  1380. @functools.wraps(decorator)
  1381. def wrapped_decorator(*args, **kwds):
  1382. func = decorator(*args, **kwds)
  1383. func = no_type_check(func)
  1384. return func
  1385. return wrapped_decorator
  1386. def _overload_dummy(*args, **kwds):
  1387. """Helper for @overload to raise when called."""
  1388. raise NotImplementedError(
  1389. "You should not call an overloaded function. "
  1390. "A series of @overload-decorated functions "
  1391. "outside a stub module should always be followed "
  1392. "by an implementation that is not @overload-ed.")
  1393. def overload(func):
  1394. """Decorator for overloaded functions/methods.
  1395. In a stub file, place two or more stub definitions for the same
  1396. function in a row, each decorated with @overload. For example:
  1397. @overload
  1398. def utf8(value: None) -> None: ...
  1399. @overload
  1400. def utf8(value: bytes) -> bytes: ...
  1401. @overload
  1402. def utf8(value: str) -> bytes: ...
  1403. In a non-stub file (i.e. a regular .py file), do the same but
  1404. follow it with an implementation. The implementation should *not*
  1405. be decorated with @overload. For example:
  1406. @overload
  1407. def utf8(value: None) -> None: ...
  1408. @overload
  1409. def utf8(value: bytes) -> bytes: ...
  1410. @overload
  1411. def utf8(value: str) -> bytes: ...
  1412. def utf8(value):
  1413. # implementation goes here
  1414. """
  1415. return _overload_dummy
  1416. _PROTO_WHITELIST = ['Callable', 'Iterable', 'Iterator',
  1417. 'Hashable', 'Sized', 'Container', 'Collection',
  1418. 'Reversible', 'ContextManager']
  1419. class _ProtocolMeta(GenericMeta):
  1420. """Internal metaclass for Protocol.
  1421. This exists so Protocol classes can be generic without deriving
  1422. from Generic.
  1423. """
  1424. def __init__(cls, *args, **kwargs):
  1425. super(_ProtocolMeta, cls).__init__(*args, **kwargs)
  1426. if not cls.__dict__.get('_is_protocol', None):
  1427. cls._is_protocol = any(b is Protocol or
  1428. isinstance(b, _ProtocolMeta) and
  1429. b.__origin__ is Protocol
  1430. for b in cls.__bases__)
  1431. if cls._is_protocol:
  1432. for base in cls.__mro__[1:]:
  1433. if not (base in (object, Generic) or
  1434. base.__module__ == '_abcoll' and
  1435. base.__name__ in _PROTO_WHITELIST or
  1436. isinstance(base, TypingMeta) and base._is_protocol or
  1437. isinstance(base, GenericMeta) and base.__origin__ is Generic):
  1438. raise TypeError('Protocols can only inherit from other protocols,'
  1439. ' got %r' % base)
  1440. cls._callable_members_only = all(callable(getattr(cls, attr))
  1441. for attr in cls._get_protocol_attrs())
  1442. def _no_init(self, *args, **kwargs):
  1443. if type(self)._is_protocol:
  1444. raise TypeError('Protocols cannot be instantiated')
  1445. cls.__init__ = _no_init
  1446. def _proto_hook(cls, other):
  1447. if not cls.__dict__.get('_is_protocol', None):
  1448. return NotImplemented
  1449. if not isinstance(other, type):
  1450. # Similar error as for issubclass(1, int)
  1451. # (also not a chance for old-style classes)
  1452. raise TypeError('issubclass() arg 1 must be a new-style class')
  1453. for attr in cls._get_protocol_attrs():
  1454. for base in other.__mro__:
  1455. if attr in base.__dict__:
  1456. if base.__dict__[attr] is None:
  1457. return NotImplemented
  1458. break
  1459. else:
  1460. return NotImplemented
  1461. return True
  1462. if '__subclasshook__' not in cls.__dict__:
  1463. cls.__subclasshook__ = classmethod(_proto_hook)
  1464. def __instancecheck__(self, instance):
  1465. # We need this method for situations where attributes are assigned in __init__
  1466. if isinstance(instance, type):
  1467. # This looks like a fundamental limitation of Python 2.
  1468. # It cannot support runtime protocol metaclasses, On Python 2 classes
  1469. # cannot be correctly inspected as instances of protocols.
  1470. return False
  1471. if ((not getattr(self, '_is_protocol', False) or
  1472. self._callable_members_only) and
  1473. issubclass(instance.__class__, self)):
  1474. return True
  1475. if self._is_protocol:
  1476. if all(hasattr(instance, attr) and
  1477. (not callable(getattr(self, attr)) or
  1478. getattr(instance, attr) is not None)
  1479. for attr in self._get_protocol_attrs()):
  1480. return True
  1481. return super(GenericMeta, self).__instancecheck__(instance)
  1482. def __subclasscheck__(self, cls):
  1483. if (self.__dict__.get('_is_protocol', None) and
  1484. not self.__dict__.get('_is_runtime_protocol', None)):
  1485. if (sys._getframe(1).f_globals['__name__'] in ['abc', 'functools'] or
  1486. # This is needed because we remove subclasses from unions on Python 2.
  1487. sys._getframe(2).f_globals['__name__'] == 'typing'):
  1488. return False
  1489. raise TypeError("Instance and class checks can only be used with"
  1490. " @runtime_checkable protocols")
  1491. if (self.__dict__.get('_is_runtime_protocol', None) and
  1492. not self._callable_members_only):
  1493. if sys._getframe(1).f_globals['__name__'] in ['abc', 'functools']:
  1494. return super(GenericMeta, self).__subclasscheck__(cls)
  1495. raise TypeError("Protocols with non-method members"
  1496. " don't support issubclass()")
  1497. return super(_ProtocolMeta, self).__subclasscheck__(cls)
  1498. def _get_protocol_attrs(self):
  1499. attrs = set()
  1500. for base in self.__mro__[:-1]: # without object
  1501. if base.__name__ in ('Protocol', 'Generic'):
  1502. continue
  1503. annotations = getattr(base, '__annotations__', {})
  1504. for attr in list(base.__dict__.keys()) + list(annotations.keys()):
  1505. if (not attr.startswith('_abc_') and attr not in (
  1506. '__abstractmethods__', '__annotations__', '__weakref__',
  1507. '_is_protocol', '_is_runtime_protocol', '__dict__',
  1508. '__args__', '__slots__', '_get_protocol_attrs',
  1509. '__next_in_mro__', '__parameters__', '__origin__',
  1510. '__orig_bases__', '__extra__', '__tree_hash__',
  1511. '__doc__', '__subclasshook__', '__init__', '__new__',
  1512. '__module__', '_MutableMapping__marker',
  1513. '__metaclass__', '_gorg', '_callable_members_only')):
  1514. attrs.add(attr)
  1515. return attrs
  1516. class Protocol(object):
  1517. """Base class for protocol classes. Protocol classes are defined as::
  1518. class Proto(Protocol):
  1519. def meth(self):
  1520. # type: () -> int
  1521. pass
  1522. Such classes are primarily used with static type checkers that recognize
  1523. structural subtyping (static duck-typing), for example::
  1524. class C:
  1525. def meth(self):
  1526. # type: () -> int
  1527. return 0
  1528. def func(x):
  1529. # type: (Proto) -> int
  1530. return x.meth()
  1531. func(C()) # Passes static type check
  1532. See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable
  1533. act as simple-minded runtime protocols that checks only the presence of
  1534. given attributes, ignoring their type signatures.
  1535. Protocol classes can be generic, they are defined as::
  1536. class GenProto(Protocol[T]):
  1537. def meth(self):
  1538. # type: () -> T
  1539. pass
  1540. """
  1541. __metaclass__ = _ProtocolMeta
  1542. __slots__ = ()
  1543. _is_protocol = True
  1544. def __new__(cls, *args, **kwds):
  1545. if cls._gorg is Protocol:
  1546. raise TypeError("Type Protocol cannot be instantiated; "
  1547. "it can be used only as a base class")
  1548. return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
  1549. def runtime_checkable(cls):
  1550. """Mark a protocol class as a runtime protocol, so that it
  1551. can be used with isinstance() and issubclass(). Raise TypeError
  1552. if applied to a non-protocol class.
  1553. This allows a simple-minded structural check very similar to the
  1554. one-offs in collections.abc such as Hashable.
  1555. """
  1556. if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
  1557. raise TypeError('@runtime_checkable can be only applied to protocol classes,'
  1558. ' got %r' % cls)
  1559. cls._is_runtime_protocol = True
  1560. return cls
  1561. # Various ABCs mimicking those in collections.abc.
  1562. # A few are simply re-exported for completeness.
  1563. Hashable = collections_abc.Hashable # Not generic.
  1564. class Iterable(Generic[T_co]):
  1565. __slots__ = ()
  1566. __extra__ = collections_abc.Iterable
  1567. class Iterator(Iterable[T_co]):
  1568. __slots__ = ()
  1569. __extra__ = collections_abc.Iterator
  1570. @runtime_checkable
  1571. class SupportsInt(Protocol):
  1572. __slots__ = ()
  1573. @abstractmethod
  1574. def __int__(self):
  1575. pass
  1576. @runtime_checkable
  1577. class SupportsFloat(Protocol):
  1578. __slots__ = ()
  1579. @abstractmethod
  1580. def __float__(self):
  1581. pass
  1582. @runtime_checkable
  1583. class SupportsComplex(Protocol):
  1584. __slots__ = ()
  1585. @abstractmethod
  1586. def __complex__(self):
  1587. pass
  1588. @runtime_checkable
  1589. class SupportsIndex(Protocol):
  1590. __slots__ = ()
  1591. @abstractmethod
  1592. def __index__(self):
  1593. pass
  1594. @runtime_checkable
  1595. class SupportsAbs(Protocol[T_co]):
  1596. __slots__ = ()
  1597. @abstractmethod
  1598. def __abs__(self):
  1599. pass
  1600. if hasattr(collections_abc, 'Reversible'):
  1601. class Reversible(Iterable[T_co]):
  1602. __slots__ = ()
  1603. __extra__ = collections_abc.Reversible
  1604. else:
  1605. @runtime_checkable
  1606. class Reversible(Protocol[T_co]):
  1607. __slots__ = ()
  1608. @abstractmethod
  1609. def __reversed__(self):
  1610. pass
  1611. Sized = collections_abc.Sized # Not generic.
  1612. class Container(Generic[T_co]):
  1613. __slots__ = ()
  1614. __extra__ = collections_abc.Container
  1615. # Callable was defined earlier.
  1616. class AbstractSet(Sized, Iterable[T_co], Container[T_co]):
  1617. __slots__ = ()
  1618. __extra__ = collections_abc.Set
  1619. class MutableSet(AbstractSet[T]):
  1620. __slots__ = ()
  1621. __extra__ = collections_abc.MutableSet
  1622. # NOTE: It is only covariant in the value type.
  1623. class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co]):
  1624. __slots__ = ()
  1625. __extra__ = collections_abc.Mapping
  1626. class MutableMapping(Mapping[KT, VT]):
  1627. __slots__ = ()
  1628. __extra__ = collections_abc.MutableMapping
  1629. if hasattr(collections_abc, 'Reversible'):
  1630. class Sequence(Sized, Reversible[T_co], Container[T_co]):
  1631. __slots__ = ()
  1632. __extra__ = collections_abc.Sequence
  1633. else:
  1634. class Sequence(Sized, Iterable[T_co], Container[T_co]):
  1635. __slots__ = ()
  1636. __extra__ = collections_abc.Sequence
  1637. class MutableSequence(Sequence[T]):
  1638. __slots__ = ()
  1639. __extra__ = collections_abc.MutableSequence
  1640. class ByteString(Sequence[int]):
  1641. pass
  1642. ByteString.register(str)
  1643. ByteString.register(bytearray)
  1644. class List(list, MutableSequence[T]):
  1645. __slots__ = ()
  1646. __extra__ = list
  1647. def __new__(cls, *args, **kwds):
  1648. if cls._gorg is List:
  1649. raise TypeError("Type List cannot be instantiated; "
  1650. "use list() instead")
  1651. return _generic_new(list, cls, *args, **kwds)
  1652. class Deque(collections.deque, MutableSequence[T]):
  1653. __slots__ = ()
  1654. __extra__ = collections.deque
  1655. def __new__(cls, *args, **kwds):
  1656. if cls._gorg is Deque:
  1657. return collections.deque(*args, **kwds)
  1658. return _generic_new(collections.deque, cls, *args, **kwds)
  1659. class Set(set, MutableSet[T]):
  1660. __slots__ = ()
  1661. __extra__ = set
  1662. def __new__(cls, *args, **kwds):
  1663. if cls._gorg is Set:
  1664. raise TypeError("Type Set cannot be instantiated; "
  1665. "use set() instead")
  1666. return _generic_new(set, cls, *args, **kwds)
  1667. class FrozenSet(frozenset, AbstractSet[T_co]):
  1668. __slots__ = ()
  1669. __extra__ = frozenset
  1670. def __new__(cls, *args, **kwds):
  1671. if cls._gorg is FrozenSet:
  1672. raise TypeError("Type FrozenSet cannot be instantiated; "
  1673. "use frozenset() instead")
  1674. return _generic_new(frozenset, cls, *args, **kwds)
  1675. class MappingView(Sized, Iterable[T_co]):
  1676. __slots__ = ()
  1677. __extra__ = collections_abc.MappingView
  1678. class KeysView(MappingView[KT], AbstractSet[KT]):
  1679. __slots__ = ()
  1680. __extra__ = collections_abc.KeysView
  1681. class ItemsView(MappingView[Tuple[KT, VT_co]],
  1682. AbstractSet[Tuple[KT, VT_co]],
  1683. Generic[KT, VT_co]):
  1684. __slots__ = ()
  1685. __extra__ = collections_abc.ItemsView
  1686. class ValuesView(MappingView[VT_co]):
  1687. __slots__ = ()
  1688. __extra__ = collections_abc.ValuesView
  1689. class ContextManager(Generic[T_co]):
  1690. __slots__ = ()
  1691. def __enter__(self):
  1692. return self
  1693. @abc.abstractmethod
  1694. def __exit__(self, exc_type, exc_value, traceback):
  1695. return None
  1696. @classmethod
  1697. def __subclasshook__(cls, C):
  1698. if cls is ContextManager:
  1699. # In Python 3.6+, it is possible to set a method to None to
  1700. # explicitly indicate that the class does not implement an ABC
  1701. # (https://bugs.python.org/issue25958), but we do not support
  1702. # that pattern here because this fallback class is only used
  1703. # in Python 3.5 and earlier.
  1704. if (any("__enter__" in B.__dict__ for B in C.__mro__) and
  1705. any("__exit__" in B.__dict__ for B in C.__mro__)):
  1706. return True
  1707. return NotImplemented
  1708. class Dict(dict, MutableMapping[KT, VT]):
  1709. __slots__ = ()
  1710. __extra__ = dict
  1711. def __new__(cls, *args, **kwds):
  1712. if cls._gorg is Dict:
  1713. raise TypeError("Type Dict cannot be instantiated; "
  1714. "use dict() instead")
  1715. return _generic_new(dict, cls, *args, **kwds)
  1716. class DefaultDict(collections.defaultdict, MutableMapping[KT, VT]):
  1717. __slots__ = ()
  1718. __extra__ = collections.defaultdict
  1719. def __new__(cls, *args, **kwds):
  1720. if cls._gorg is DefaultDict:
  1721. return collections.defaultdict(*args, **kwds)
  1722. return _generic_new(collections.defaultdict, cls, *args, **kwds)
  1723. class Counter(collections.Counter, Dict[T, int]):
  1724. __slots__ = ()
  1725. __extra__ = collections.Counter
  1726. def __new__(cls, *args, **kwds):
  1727. if cls._gorg is Counter:
  1728. return collections.Counter(*args, **kwds)
  1729. return _generic_new(collections.Counter, cls, *args, **kwds)
  1730. # Determine what base class to use for Generator.
  1731. if hasattr(collections_abc, 'Generator'):
  1732. # Sufficiently recent versions of 3.5 have a Generator ABC.
  1733. _G_base = collections_abc.Generator
  1734. else:
  1735. # Fall back on the exact type.
  1736. _G_base = types.GeneratorType
  1737. class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]):
  1738. __slots__ = ()
  1739. __extra__ = _G_base
  1740. def __new__(cls, *args, **kwds):
  1741. if cls._gorg is Generator:
  1742. raise TypeError("Type Generator cannot be instantiated; "
  1743. "create a subclass instead")
  1744. return _generic_new(_G_base, cls, *args, **kwds)
  1745. # Internal type variable used for Type[].
  1746. CT_co = TypeVar('CT_co', covariant=True, bound=type)
  1747. # This is not a real generic class. Don't use outside annotations.
  1748. class Type(Generic[CT_co]):
  1749. """A special construct usable to annotate class objects.
  1750. For example, suppose we have the following classes::
  1751. class User: ... # Abstract base for User classes
  1752. class BasicUser(User): ...
  1753. class ProUser(User): ...
  1754. class TeamUser(User): ...
  1755. And a function that takes a class argument that's a subclass of
  1756. User and returns an instance of the corresponding class::
  1757. U = TypeVar('U', bound=User)
  1758. def new_user(user_class: Type[U]) -> U:
  1759. user = user_class()
  1760. # (Here we could write the user object to a database)
  1761. return user
  1762. joe = new_user(BasicUser)
  1763. At this point the type checker knows that joe has type BasicUser.
  1764. """
  1765. __slots__ = ()
  1766. __extra__ = type
  1767. def NamedTuple(typename, fields):
  1768. """Typed version of namedtuple.
  1769. Usage::
  1770. Employee = typing.NamedTuple('Employee', [('name', str), ('id', int)])
  1771. This is equivalent to::
  1772. Employee = collections.namedtuple('Employee', ['name', 'id'])
  1773. The resulting class has one extra attribute: _field_types,
  1774. giving a dict mapping field names to types. (The field names
  1775. are in the _fields attribute, which is part of the namedtuple
  1776. API.)
  1777. """
  1778. fields = [(n, t) for n, t in fields]
  1779. cls = collections.namedtuple(typename, [n for n, t in fields])
  1780. cls._field_types = dict(fields)
  1781. # Set the module to the caller's module (otherwise it'd be 'typing').
  1782. try:
  1783. cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
  1784. except (AttributeError, ValueError):
  1785. pass
  1786. return cls
  1787. def _check_fails(cls, other):
  1788. try:
  1789. if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools', 'typing']:
  1790. # Typed dicts are only for static structural subtyping.
  1791. raise TypeError('TypedDict does not support instance and class checks')
  1792. except (AttributeError, ValueError):
  1793. pass
  1794. return False
  1795. def _dict_new(cls, *args, **kwargs):
  1796. return dict(*args, **kwargs)
  1797. def _typeddict_new(cls, _typename, _fields=None, **kwargs):
  1798. total = kwargs.pop('total', True)
  1799. if _fields is None:
  1800. _fields = kwargs
  1801. elif kwargs:
  1802. raise TypeError("TypedDict takes either a dict or keyword arguments,"
  1803. " but not both")
  1804. ns = {'__annotations__': dict(_fields), '__total__': total}
  1805. try:
  1806. # Setting correct module is necessary to make typed dict classes pickleable.
  1807. ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
  1808. except (AttributeError, ValueError):
  1809. pass
  1810. return _TypedDictMeta(_typename, (), ns)
  1811. class _TypedDictMeta(type):
  1812. def __new__(cls, name, bases, ns, total=True):
  1813. # Create new typed dict class object.
  1814. # This method is called directly when TypedDict is subclassed,
  1815. # or via _typeddict_new when TypedDict is instantiated. This way
  1816. # TypedDict supports all three syntaxes described in its docstring.
  1817. # Subclasses and instances of TypedDict return actual dictionaries
  1818. # via _dict_new.
  1819. ns['__new__'] = _typeddict_new if name == b'TypedDict' else _dict_new
  1820. tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)
  1821. anns = ns.get('__annotations__', {})
  1822. msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
  1823. anns = {n: _type_check(tp, msg) for n, tp in anns.items()}
  1824. for base in bases:
  1825. anns.update(base.__dict__.get('__annotations__', {}))
  1826. tp_dict.__annotations__ = anns
  1827. if not hasattr(tp_dict, '__total__'):
  1828. tp_dict.__total__ = total
  1829. return tp_dict
  1830. __instancecheck__ = __subclasscheck__ = _check_fails
  1831. TypedDict = _TypedDictMeta(b'TypedDict', (dict,), {})
  1832. TypedDict.__module__ = __name__
  1833. TypedDict.__doc__ = \
  1834. """A simple typed name space. At runtime it is equivalent to a plain dict.
  1835. TypedDict creates a dictionary type that expects all of its
  1836. instances to have a certain set of keys, with each key
  1837. associated with a value of a consistent type. This expectation
  1838. is not checked at runtime but is only enforced by type checkers.
  1839. Usage::
  1840. Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
  1841. a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
  1842. b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
  1843. assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
  1844. The type info could be accessed via Point2D.__annotations__. TypedDict
  1845. supports an additional equivalent form::
  1846. Point2D = TypedDict('Point2D', x=int, y=int, label=str)
  1847. """
  1848. def NewType(name, tp):
  1849. """NewType creates simple unique types with almost zero
  1850. runtime overhead. NewType(name, tp) is considered a subtype of tp
  1851. by static type checkers. At runtime, NewType(name, tp) returns
  1852. a dummy function that simply returns its argument. Usage::
  1853. UserId = NewType('UserId', int)
  1854. def name_by_id(user_id):
  1855. # type: (UserId) -> str
  1856. ...
  1857. UserId('user') # Fails type check
  1858. name_by_id(42) # Fails type check
  1859. name_by_id(UserId(42)) # OK
  1860. num = UserId(5) + 1 # type: int
  1861. """
  1862. def new_type(x):
  1863. return x
  1864. # Some versions of Python 2 complain because of making all strings unicode
  1865. new_type.__name__ = str(name)
  1866. new_type.__supertype__ = tp
  1867. return new_type
  1868. # Python-version-specific alias (Python 2: unicode; Python 3: str)
  1869. Text = unicode
  1870. # Constant that's True when type checking, but False here.
  1871. TYPE_CHECKING = False
  1872. class IO(Generic[AnyStr]):
  1873. """Generic base class for TextIO and BinaryIO.
  1874. This is an abstract, generic version of the return of open().
  1875. NOTE: This does not distinguish between the different possible
  1876. classes (text vs. binary, read vs. write vs. read/write,
  1877. append-only, unbuffered). The TextIO and BinaryIO subclasses
  1878. below capture the distinctions between text vs. binary, which is
  1879. pervasive in the interface; however we currently do not offer a
  1880. way to track the other distinctions in the type system.
  1881. """
  1882. __slots__ = ()
  1883. @abstractproperty
  1884. def mode(self):
  1885. pass
  1886. @abstractproperty
  1887. def name(self):
  1888. pass
  1889. @abstractmethod
  1890. def close(self):
  1891. pass
  1892. @abstractproperty
  1893. def closed(self):
  1894. pass
  1895. @abstractmethod
  1896. def fileno(self):
  1897. pass
  1898. @abstractmethod
  1899. def flush(self):
  1900. pass
  1901. @abstractmethod
  1902. def isatty(self):
  1903. pass
  1904. @abstractmethod
  1905. def read(self, n=-1):
  1906. pass
  1907. @abstractmethod
  1908. def readable(self):
  1909. pass
  1910. @abstractmethod
  1911. def readline(self, limit=-1):
  1912. pass
  1913. @abstractmethod
  1914. def readlines(self, hint=-1):
  1915. pass
  1916. @abstractmethod
  1917. def seek(self, offset, whence=0):
  1918. pass
  1919. @abstractmethod
  1920. def seekable(self):
  1921. pass
  1922. @abstractmethod
  1923. def tell(self):
  1924. pass
  1925. @abstractmethod
  1926. def truncate(self, size=None):
  1927. pass
  1928. @abstractmethod
  1929. def writable(self):
  1930. pass
  1931. @abstractmethod
  1932. def write(self, s):
  1933. pass
  1934. @abstractmethod
  1935. def writelines(self, lines):
  1936. pass
  1937. @abstractmethod
  1938. def __enter__(self):
  1939. pass
  1940. @abstractmethod
  1941. def __exit__(self, type, value, traceback):
  1942. pass
  1943. class BinaryIO(IO[bytes]):
  1944. """Typed version of the return of open() in binary mode."""
  1945. __slots__ = ()
  1946. @abstractmethod
  1947. def write(self, s):
  1948. pass
  1949. @abstractmethod
  1950. def __enter__(self):
  1951. pass
  1952. class TextIO(IO[unicode]):
  1953. """Typed version of the return of open() in text mode."""
  1954. __slots__ = ()
  1955. @abstractproperty
  1956. def buffer(self):
  1957. pass
  1958. @abstractproperty
  1959. def encoding(self):
  1960. pass
  1961. @abstractproperty
  1962. def errors(self):
  1963. pass
  1964. @abstractproperty
  1965. def line_buffering(self):
  1966. pass
  1967. @abstractproperty
  1968. def newlines(self):
  1969. pass
  1970. @abstractmethod
  1971. def __enter__(self):
  1972. pass
  1973. class io(object):
  1974. """Wrapper namespace for IO generic classes."""
  1975. __all__ = ['IO', 'TextIO', 'BinaryIO']
  1976. IO = IO
  1977. TextIO = TextIO
  1978. BinaryIO = BinaryIO
  1979. io.__name__ = __name__ + b'.io'
  1980. sys.modules[io.__name__] = io
  1981. Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
  1982. lambda p: p.pattern)
  1983. Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
  1984. lambda m: m.re.pattern)
  1985. class re(object):
  1986. """Wrapper namespace for re type aliases."""
  1987. __all__ = ['Pattern', 'Match']
  1988. Pattern = Pattern
  1989. Match = Match
  1990. re.__name__ = __name__ + b'.re'
  1991. sys.modules[re.__name__] = re