test_typing.py 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706
  1. from __future__ import absolute_import, unicode_literals
  2. import collections
  3. import contextlib
  4. import os
  5. import pickle
  6. import re
  7. import subprocess
  8. import sys
  9. import abc
  10. import types
  11. from unittest import TestCase, main, SkipTest
  12. from copy import copy, deepcopy
  13. from typing import Any, NoReturn
  14. from typing import TypeVar, AnyStr
  15. from typing import T, KT, VT # Not in __all__.
  16. from typing import Union, Optional
  17. from typing import Tuple, List, MutableMapping
  18. from typing import Callable
  19. from typing import Generic, ClassVar, GenericMeta, Final, Literal
  20. from typing import cast
  21. from typing import Type, Protocol, runtime_checkable
  22. from typing import NewType
  23. from typing import NamedTuple, TypedDict
  24. from typing import Pattern, Match
  25. import typing
  26. import weakref
  27. import collections
  28. class BaseTestCase(TestCase):
  29. def assertIsSubclass(self, cls, class_or_tuple, msg=None):
  30. if not issubclass(cls, class_or_tuple):
  31. message = '%r is not a subclass of %r' % (cls, class_or_tuple)
  32. if msg is not None:
  33. message += ' : %s' % msg
  34. raise self.failureException(message)
  35. def assertNotIsSubclass(self, cls, class_or_tuple, msg=None):
  36. if issubclass(cls, class_or_tuple):
  37. message = '%r is a subclass of %r' % (cls, class_or_tuple)
  38. if msg is not None:
  39. message += ' : %s' % msg
  40. raise self.failureException(message)
  41. def clear_caches(self):
  42. for f in typing._cleanups:
  43. f()
  44. class Employee(object):
  45. pass
  46. class Manager(Employee):
  47. pass
  48. class Founder(Employee):
  49. pass
  50. class ManagingFounder(Manager, Founder):
  51. pass
  52. class AnyTests(BaseTestCase):
  53. def test_any_instance_type_error(self):
  54. with self.assertRaises(TypeError):
  55. isinstance(42, Any)
  56. def test_any_subclass_type_error(self):
  57. with self.assertRaises(TypeError):
  58. issubclass(Employee, Any)
  59. with self.assertRaises(TypeError):
  60. issubclass(Any, Employee)
  61. def test_repr(self):
  62. self.assertEqual(repr(Any), 'typing.Any')
  63. def test_errors(self):
  64. with self.assertRaises(TypeError):
  65. issubclass(42, Any)
  66. with self.assertRaises(TypeError):
  67. Any[int] # Any is not a generic type.
  68. def test_cannot_subclass(self):
  69. with self.assertRaises(TypeError):
  70. class A(Any):
  71. pass
  72. with self.assertRaises(TypeError):
  73. class A(type(Any)):
  74. pass
  75. def test_cannot_instantiate(self):
  76. with self.assertRaises(TypeError):
  77. Any()
  78. with self.assertRaises(TypeError):
  79. type(Any)()
  80. def test_any_is_subclass(self):
  81. # These expressions must simply not fail.
  82. typing.Match[Any]
  83. typing.Pattern[Any]
  84. typing.IO[Any]
  85. class NoReturnTests(BaseTestCase):
  86. def test_noreturn_instance_type_error(self):
  87. with self.assertRaises(TypeError):
  88. isinstance(42, NoReturn)
  89. def test_noreturn_subclass_type_error(self):
  90. with self.assertRaises(TypeError):
  91. issubclass(Employee, NoReturn)
  92. with self.assertRaises(TypeError):
  93. issubclass(NoReturn, Employee)
  94. def test_repr(self):
  95. self.assertEqual(repr(NoReturn), 'typing.NoReturn')
  96. def test_not_generic(self):
  97. with self.assertRaises(TypeError):
  98. NoReturn[int]
  99. def test_cannot_subclass(self):
  100. with self.assertRaises(TypeError):
  101. class A(NoReturn):
  102. pass
  103. with self.assertRaises(TypeError):
  104. class A(type(NoReturn)):
  105. pass
  106. def test_cannot_instantiate(self):
  107. with self.assertRaises(TypeError):
  108. NoReturn()
  109. with self.assertRaises(TypeError):
  110. type(NoReturn)()
  111. class TypeVarTests(BaseTestCase):
  112. def test_basic_plain(self):
  113. T = TypeVar('T')
  114. # T equals itself.
  115. self.assertEqual(T, T)
  116. # T is an instance of TypeVar
  117. self.assertIsInstance(T, TypeVar)
  118. def test_typevar_instance_type_error(self):
  119. T = TypeVar('T')
  120. with self.assertRaises(TypeError):
  121. isinstance(42, T)
  122. def test_typevar_subclass_type_error(self):
  123. T = TypeVar('T')
  124. with self.assertRaises(TypeError):
  125. issubclass(int, T)
  126. with self.assertRaises(TypeError):
  127. issubclass(T, int)
  128. def test_constrained_error(self):
  129. with self.assertRaises(TypeError):
  130. X = TypeVar('X', int)
  131. X
  132. def test_union_unique(self):
  133. X = TypeVar('X')
  134. Y = TypeVar('Y')
  135. self.assertNotEqual(X, Y)
  136. self.assertEqual(Union[X], X)
  137. self.assertNotEqual(Union[X], Union[X, Y])
  138. self.assertEqual(Union[X, X], X)
  139. self.assertNotEqual(Union[X, int], Union[X])
  140. self.assertNotEqual(Union[X, int], Union[int])
  141. self.assertEqual(Union[X, int].__args__, (X, int))
  142. self.assertEqual(Union[X, int].__parameters__, (X,))
  143. self.assertIs(Union[X, int].__origin__, Union)
  144. def test_union_constrained(self):
  145. A = TypeVar('A', str, bytes)
  146. self.assertNotEqual(Union[A, str], Union[A])
  147. def test_repr(self):
  148. self.assertEqual(repr(T), '~T')
  149. self.assertEqual(repr(KT), '~KT')
  150. self.assertEqual(repr(VT), '~VT')
  151. self.assertEqual(repr(AnyStr), '~AnyStr')
  152. T_co = TypeVar('T_co', covariant=True)
  153. self.assertEqual(repr(T_co), '+T_co')
  154. T_contra = TypeVar('T_contra', contravariant=True)
  155. self.assertEqual(repr(T_contra), '-T_contra')
  156. def test_no_redefinition(self):
  157. self.assertNotEqual(TypeVar('T'), TypeVar('T'))
  158. self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str))
  159. def test_cannot_subclass_vars(self):
  160. with self.assertRaises(TypeError):
  161. class V(TypeVar('T')):
  162. pass
  163. def test_cannot_subclass_var_itself(self):
  164. with self.assertRaises(TypeError):
  165. class V(TypeVar):
  166. pass
  167. def test_cannot_instantiate_vars(self):
  168. with self.assertRaises(TypeError):
  169. TypeVar('A')()
  170. def test_bound_errors(self):
  171. with self.assertRaises(TypeError):
  172. TypeVar('X', bound=42)
  173. with self.assertRaises(TypeError):
  174. TypeVar('X', str, float, bound=Employee)
  175. def test_no_bivariant(self):
  176. with self.assertRaises(ValueError):
  177. TypeVar('T', covariant=True, contravariant=True)
  178. class UnionTests(BaseTestCase):
  179. def test_basics(self):
  180. u = Union[int, float]
  181. self.assertNotEqual(u, Union)
  182. def test_subclass_error(self):
  183. with self.assertRaises(TypeError):
  184. issubclass(int, Union)
  185. with self.assertRaises(TypeError):
  186. issubclass(Union, int)
  187. with self.assertRaises(TypeError):
  188. issubclass(int, Union[int, str])
  189. with self.assertRaises(TypeError):
  190. issubclass(Union[int, str], int)
  191. def test_union_any(self):
  192. u = Union[Any]
  193. self.assertEqual(u, Any)
  194. u1 = Union[int, Any]
  195. u2 = Union[Any, int]
  196. u3 = Union[Any, object]
  197. self.assertEqual(u1, u2)
  198. self.assertNotEqual(u1, Any)
  199. self.assertNotEqual(u2, Any)
  200. self.assertNotEqual(u3, Any)
  201. def test_union_object(self):
  202. u = Union[object]
  203. self.assertEqual(u, object)
  204. u = Union[int, object]
  205. self.assertEqual(u, object)
  206. u = Union[object, int]
  207. self.assertEqual(u, object)
  208. def test_unordered(self):
  209. u1 = Union[int, float]
  210. u2 = Union[float, int]
  211. self.assertEqual(u1, u2)
  212. def test_single_class_disappears(self):
  213. t = Union[Employee]
  214. self.assertIs(t, Employee)
  215. def test_base_class_disappears(self):
  216. u = Union[Employee, Manager, int]
  217. self.assertEqual(u, Union[int, Employee])
  218. u = Union[Manager, int, Employee]
  219. self.assertEqual(u, Union[int, Employee])
  220. u = Union[Employee, Manager]
  221. self.assertIs(u, Employee)
  222. def test_union_union(self):
  223. u = Union[int, float]
  224. v = Union[u, Employee]
  225. self.assertEqual(v, Union[int, float, Employee])
  226. def test_repr(self):
  227. self.assertEqual(repr(Union), 'typing.Union')
  228. u = Union[Employee, int]
  229. self.assertEqual(repr(u), 'typing.Union[%s.Employee, int]' % __name__)
  230. u = Union[int, Employee]
  231. self.assertEqual(repr(u), 'typing.Union[int, %s.Employee]' % __name__)
  232. T = TypeVar('T')
  233. u = Union[T, int][int]
  234. self.assertEqual(repr(u), repr(int))
  235. u = Union[List[int], int]
  236. self.assertEqual(repr(u), 'typing.Union[typing.List[int], int]')
  237. def test_cannot_subclass(self):
  238. with self.assertRaises(TypeError):
  239. class C(Union):
  240. pass
  241. with self.assertRaises(TypeError):
  242. class C(type(Union)):
  243. pass
  244. with self.assertRaises(TypeError):
  245. class C(Union[int, str]):
  246. pass
  247. def test_cannot_instantiate(self):
  248. with self.assertRaises(TypeError):
  249. Union()
  250. u = Union[int, float]
  251. with self.assertRaises(TypeError):
  252. u()
  253. with self.assertRaises(TypeError):
  254. type(u)()
  255. def test_union_generalization(self):
  256. self.assertFalse(Union[str, typing.Iterable[int]] == str)
  257. self.assertFalse(Union[str, typing.Iterable[int]] == typing.Iterable[int])
  258. self.assertTrue(Union[str, typing.Iterable] == typing.Iterable)
  259. def test_union_compare_other(self):
  260. self.assertNotEqual(Union, object)
  261. self.assertNotEqual(Union, Any)
  262. self.assertNotEqual(ClassVar, Union)
  263. self.assertNotEqual(Optional, Union)
  264. self.assertNotEqual([None], Optional)
  265. self.assertNotEqual(Optional, typing.Mapping)
  266. self.assertNotEqual(Optional[typing.MutableMapping], Union)
  267. def test_optional(self):
  268. o = Optional[int]
  269. u = Union[int, None]
  270. self.assertEqual(o, u)
  271. def test_empty(self):
  272. with self.assertRaises(TypeError):
  273. Union[()]
  274. def test_union_instance_type_error(self):
  275. with self.assertRaises(TypeError):
  276. isinstance(42, Union[int, str])
  277. def test_no_eval_union(self):
  278. u = Union[int, str]
  279. self.assertIs(u._eval_type({}, {}), u)
  280. def test_function_repr_union(self):
  281. def fun(): pass
  282. self.assertEqual(repr(Union[fun, int]), 'typing.Union[fun, int]')
  283. def test_union_str_pattern(self):
  284. # Shouldn't crash; see http://bugs.python.org/issue25390
  285. A = Union[str, Pattern]
  286. A
  287. def test_etree(self):
  288. # See https://github.com/python/typing/issues/229
  289. # (Only relevant for Python 2.)
  290. try:
  291. from xml.etree.cElementTree import Element
  292. except ImportError:
  293. raise SkipTest("cElementTree not found")
  294. Union[Element, str] # Shouldn't crash
  295. def Elem(*args):
  296. return Element(*args)
  297. Union[Elem, str] # Nor should this
  298. class TupleTests(BaseTestCase):
  299. def test_basics(self):
  300. with self.assertRaises(TypeError):
  301. issubclass(Tuple, Tuple[int, str])
  302. with self.assertRaises(TypeError):
  303. issubclass(tuple, Tuple[int, str])
  304. class TP(tuple): pass
  305. self.assertTrue(issubclass(tuple, Tuple))
  306. self.assertTrue(issubclass(TP, Tuple))
  307. def test_equality(self):
  308. self.assertEqual(Tuple[int], Tuple[int])
  309. self.assertEqual(Tuple[int, ...], Tuple[int, ...])
  310. self.assertNotEqual(Tuple[int], Tuple[int, int])
  311. self.assertNotEqual(Tuple[int], Tuple[int, ...])
  312. def test_tuple_subclass(self):
  313. class MyTuple(tuple):
  314. pass
  315. self.assertTrue(issubclass(MyTuple, Tuple))
  316. def test_tuple_instance_type_error(self):
  317. with self.assertRaises(TypeError):
  318. isinstance((0, 0), Tuple[int, int])
  319. isinstance((0, 0), Tuple)
  320. def test_repr(self):
  321. self.assertEqual(repr(Tuple), 'typing.Tuple')
  322. self.assertEqual(repr(Tuple[()]), 'typing.Tuple[()]')
  323. self.assertEqual(repr(Tuple[int, float]), 'typing.Tuple[int, float]')
  324. self.assertEqual(repr(Tuple[int, ...]), 'typing.Tuple[int, ...]')
  325. def test_errors(self):
  326. with self.assertRaises(TypeError):
  327. issubclass(42, Tuple)
  328. with self.assertRaises(TypeError):
  329. issubclass(42, Tuple[int])
  330. class CallableTests(BaseTestCase):
  331. def test_self_subclass(self):
  332. with self.assertRaises(TypeError):
  333. self.assertTrue(issubclass(type(lambda x: x), Callable[[int], int]))
  334. self.assertTrue(issubclass(type(lambda x: x), Callable))
  335. def test_eq_hash(self):
  336. self.assertEqual(Callable[[int], int], Callable[[int], int])
  337. self.assertEqual(len({Callable[[int], int], Callable[[int], int]}), 1)
  338. self.assertNotEqual(Callable[[int], int], Callable[[int], str])
  339. self.assertNotEqual(Callable[[int], int], Callable[[str], int])
  340. self.assertNotEqual(Callable[[int], int], Callable[[int, int], int])
  341. self.assertNotEqual(Callable[[int], int], Callable[[], int])
  342. self.assertNotEqual(Callable[[int], int], Callable)
  343. def test_cannot_instantiate(self):
  344. with self.assertRaises(TypeError):
  345. Callable()
  346. with self.assertRaises(TypeError):
  347. type(Callable)()
  348. c = Callable[[int], str]
  349. with self.assertRaises(TypeError):
  350. c()
  351. with self.assertRaises(TypeError):
  352. type(c)()
  353. def test_callable_wrong_forms(self):
  354. with self.assertRaises(TypeError):
  355. Callable[(), int]
  356. with self.assertRaises(TypeError):
  357. Callable[[()], int]
  358. with self.assertRaises(TypeError):
  359. Callable[[int, 1], 2]
  360. with self.assertRaises(TypeError):
  361. Callable[int]
  362. def test_callable_instance_works(self):
  363. def f():
  364. pass
  365. self.assertIsInstance(f, Callable)
  366. self.assertNotIsInstance(None, Callable)
  367. def test_callable_instance_type_error(self):
  368. def f():
  369. pass
  370. with self.assertRaises(TypeError):
  371. self.assertIsInstance(f, Callable[[], None])
  372. with self.assertRaises(TypeError):
  373. self.assertIsInstance(f, Callable[[], Any])
  374. with self.assertRaises(TypeError):
  375. self.assertNotIsInstance(None, Callable[[], None])
  376. with self.assertRaises(TypeError):
  377. self.assertNotIsInstance(None, Callable[[], Any])
  378. def test_repr(self):
  379. ct0 = Callable[[], bool]
  380. self.assertEqual(repr(ct0), 'typing.Callable[[], bool]')
  381. ct2 = Callable[[str, float], int]
  382. self.assertEqual(repr(ct2), 'typing.Callable[[str, float], int]')
  383. ctv = Callable[..., str]
  384. self.assertEqual(repr(ctv), 'typing.Callable[..., str]')
  385. def test_ellipsis_in_generic(self):
  386. # Shouldn't crash; see https://github.com/python/typing/issues/259
  387. typing.List[Callable[..., str]]
  388. XK = TypeVar('XK', unicode, bytes)
  389. XV = TypeVar('XV')
  390. class SimpleMapping(Generic[XK, XV]):
  391. def __getitem__(self, key):
  392. pass
  393. def __setitem__(self, key, value):
  394. pass
  395. def get(self, key, default=None):
  396. pass
  397. class MySimpleMapping(SimpleMapping[XK, XV]):
  398. def __init__(self):
  399. self.store = {}
  400. def __getitem__(self, key):
  401. return self.store[key]
  402. def __setitem__(self, key, value):
  403. self.store[key] = value
  404. def get(self, key, default=None):
  405. try:
  406. return self.store[key]
  407. except KeyError:
  408. return default
  409. class ProtocolTests(BaseTestCase):
  410. def test_basic_protocol(self):
  411. @runtime_checkable
  412. class P(Protocol):
  413. def meth(self):
  414. pass
  415. class C(object): pass
  416. class D(object):
  417. def meth(self):
  418. pass
  419. def f():
  420. pass
  421. self.assertIsSubclass(D, P)
  422. self.assertIsInstance(D(), P)
  423. self.assertNotIsSubclass(C, P)
  424. self.assertNotIsInstance(C(), P)
  425. self.assertNotIsSubclass(types.FunctionType, P)
  426. self.assertNotIsInstance(f, P)
  427. def test_everything_implements_empty_protocol(self):
  428. @runtime_checkable
  429. class Empty(Protocol): pass
  430. class C(object): pass
  431. def f():
  432. pass
  433. for thing in (object, type, tuple, C, types.FunctionType):
  434. self.assertIsSubclass(thing, Empty)
  435. for thing in (object(), 1, (), typing, f):
  436. self.assertIsInstance(thing, Empty)
  437. def test_function_implements_protocol(self):
  438. @runtime_checkable
  439. class Function(Protocol):
  440. def __call__(self, *args, **kwargs):
  441. pass
  442. def f():
  443. pass
  444. self.assertIsInstance(f, Function)
  445. def test_no_inheritance_from_nominal(self):
  446. class C(object): pass
  447. class BP(Protocol): pass
  448. with self.assertRaises(TypeError):
  449. class P(C, Protocol):
  450. pass
  451. with self.assertRaises(TypeError):
  452. class P(Protocol, C):
  453. pass
  454. with self.assertRaises(TypeError):
  455. class P(BP, C, Protocol):
  456. pass
  457. class D(BP, C): pass
  458. class E(C, BP): pass
  459. self.assertNotIsInstance(D(), E)
  460. self.assertNotIsInstance(E(), D)
  461. def test_no_instantiation(self):
  462. class P(Protocol): pass
  463. with self.assertRaises(TypeError):
  464. P()
  465. class C(P): pass
  466. self.assertIsInstance(C(), C)
  467. T = typing.TypeVar('T')
  468. class PG(Protocol[T]): pass
  469. with self.assertRaises(TypeError):
  470. PG()
  471. with self.assertRaises(TypeError):
  472. PG[int]()
  473. with self.assertRaises(TypeError):
  474. PG[T]()
  475. class CG(PG[T]): pass
  476. self.assertIsInstance(CG[int](), CG)
  477. def test_cannot_instantiate_abstract(self):
  478. @runtime_checkable
  479. class P(Protocol):
  480. @abc.abstractmethod
  481. def ameth(self):
  482. raise NotImplementedError
  483. class B(P):
  484. pass
  485. class C(B):
  486. def ameth(self):
  487. return 26
  488. with self.assertRaises(TypeError):
  489. B()
  490. self.assertIsInstance(C(), P)
  491. def test_subprotocols_extending(self):
  492. class P1(Protocol):
  493. def meth1(self):
  494. pass
  495. @runtime_checkable
  496. class P2(P1, Protocol):
  497. def meth2(self):
  498. pass
  499. class C(object):
  500. def meth1(self):
  501. pass
  502. def meth2(self):
  503. pass
  504. class C1(object):
  505. def meth1(self):
  506. pass
  507. class C2(object):
  508. def meth2(self):
  509. pass
  510. self.assertNotIsInstance(C1(), P2)
  511. self.assertNotIsInstance(C2(), P2)
  512. self.assertNotIsSubclass(C1, P2)
  513. self.assertNotIsSubclass(C2, P2)
  514. self.assertIsInstance(C(), P2)
  515. self.assertIsSubclass(C, P2)
  516. def test_subprotocols_merging(self):
  517. class P1(Protocol):
  518. def meth1(self):
  519. pass
  520. class P2(Protocol):
  521. def meth2(self):
  522. pass
  523. @runtime_checkable
  524. class P(P1, P2, Protocol):
  525. pass
  526. class C(object):
  527. def meth1(self):
  528. pass
  529. def meth2(self):
  530. pass
  531. class C1(object):
  532. def meth1(self):
  533. pass
  534. class C2(object):
  535. def meth2(self):
  536. pass
  537. self.assertNotIsInstance(C1(), P)
  538. self.assertNotIsInstance(C2(), P)
  539. self.assertNotIsSubclass(C1, P)
  540. self.assertNotIsSubclass(C2, P)
  541. self.assertIsInstance(C(), P)
  542. self.assertIsSubclass(C, P)
  543. def test_protocols_issubclass(self):
  544. T = typing.TypeVar('T')
  545. @runtime_checkable
  546. class P(Protocol):
  547. def x(self): pass
  548. @runtime_checkable
  549. class PG(Protocol[T]):
  550. def x(self): pass
  551. class BadP(Protocol):
  552. def x(self): pass
  553. class BadPG(Protocol[T]):
  554. def x(self): pass
  555. class C(object):
  556. def x(self): pass
  557. self.assertIsSubclass(C, P)
  558. self.assertIsSubclass(C, PG)
  559. self.assertIsSubclass(BadP, PG)
  560. self.assertIsSubclass(PG[int], PG)
  561. self.assertIsSubclass(BadPG[int], P)
  562. self.assertIsSubclass(BadPG[T], PG)
  563. with self.assertRaises(TypeError):
  564. issubclass(C, PG[T])
  565. with self.assertRaises(TypeError):
  566. issubclass(C, PG[C])
  567. with self.assertRaises(TypeError):
  568. issubclass(C, BadP)
  569. with self.assertRaises(TypeError):
  570. issubclass(C, BadPG)
  571. with self.assertRaises(TypeError):
  572. issubclass(P, PG[T])
  573. with self.assertRaises(TypeError):
  574. issubclass(PG, PG[int])
  575. def test_protocols_issubclass_non_callable(self):
  576. class C(object):
  577. x = 1
  578. @runtime_checkable
  579. class PNonCall(Protocol):
  580. x = 1
  581. with self.assertRaises(TypeError):
  582. issubclass(C, PNonCall)
  583. self.assertIsInstance(C(), PNonCall)
  584. PNonCall.register(C)
  585. with self.assertRaises(TypeError):
  586. issubclass(C, PNonCall)
  587. self.assertIsInstance(C(), PNonCall)
  588. # check that non-protocol subclasses are not affected
  589. class D(PNonCall): pass
  590. self.assertNotIsSubclass(C, D)
  591. self.assertNotIsInstance(C(), D)
  592. D.register(C)
  593. self.assertIsSubclass(C, D)
  594. self.assertIsInstance(C(), D)
  595. with self.assertRaises(TypeError):
  596. issubclass(D, PNonCall)
  597. def test_protocols_isinstance(self):
  598. T = typing.TypeVar('T')
  599. @runtime_checkable
  600. class P(Protocol):
  601. def meth(x): pass
  602. @runtime_checkable
  603. class PG(Protocol[T]):
  604. def meth(x): pass
  605. class BadP(Protocol):
  606. def meth(x): pass
  607. class BadPG(Protocol[T]):
  608. def meth(x): pass
  609. class C(object):
  610. def meth(x): pass
  611. self.assertIsInstance(C(), P)
  612. self.assertIsInstance(C(), PG)
  613. with self.assertRaises(TypeError):
  614. isinstance(C(), PG[T])
  615. with self.assertRaises(TypeError):
  616. isinstance(C(), PG[C])
  617. with self.assertRaises(TypeError):
  618. isinstance(C(), BadP)
  619. with self.assertRaises(TypeError):
  620. isinstance(C(), BadPG)
  621. def test_protocols_isinstance_init(self):
  622. T = typing.TypeVar('T')
  623. @runtime_checkable
  624. class P(Protocol):
  625. x = 1
  626. @runtime_checkable
  627. class PG(Protocol[T]):
  628. x = 1
  629. class C(object):
  630. def __init__(self, x):
  631. self.x = x
  632. self.assertIsInstance(C(1), P)
  633. self.assertIsInstance(C(1), PG)
  634. def test_protocol_checks_after_subscript(self):
  635. class P(Protocol[T]): pass
  636. class C(P[T]): pass
  637. class Old1: pass
  638. class New1(object): pass
  639. class Old2: pass
  640. class New2(object): pass
  641. CA = C[Any] # noqa
  642. self.assertNotIsInstance(Old1(), C)
  643. self.assertNotIsInstance(New1(), C)
  644. self.assertNotIsSubclass(Old2, C)
  645. self.assertNotIsSubclass(New2, C)
  646. class D1(C[Any]): pass
  647. class D2(C[Any]): pass
  648. CI = C[int] # noqa
  649. self.assertIsInstance(D1(), C)
  650. self.assertIsSubclass(D2, C)
  651. def test_protocols_support_register(self):
  652. @runtime_checkable
  653. class P(Protocol):
  654. x = 1
  655. class PM(Protocol):
  656. def meth(self): pass
  657. class D(PM): pass
  658. class C(object): pass
  659. D.register(C)
  660. P.register(C)
  661. self.assertIsInstance(C(), P)
  662. self.assertIsInstance(C(), D)
  663. def test_none_on_non_callable_doesnt_block_implementation(self):
  664. @runtime_checkable
  665. class P(Protocol):
  666. x = 1
  667. class A(object):
  668. x = 1
  669. class B(A):
  670. x = None
  671. class C(object):
  672. def __init__(self):
  673. self.x = None
  674. self.assertIsInstance(B(), P)
  675. self.assertIsInstance(C(), P)
  676. def test_none_on_callable_blocks_implementation(self):
  677. @runtime_checkable
  678. class P(Protocol):
  679. def x(self): pass
  680. class A(object):
  681. def x(self): pass
  682. class B(A):
  683. x = None
  684. class C(object):
  685. def __init__(self):
  686. self.x = None
  687. self.assertNotIsInstance(B(), P)
  688. self.assertNotIsInstance(C(), P)
  689. def test_non_protocol_subclasses(self):
  690. class P(Protocol):
  691. x = 1
  692. @runtime_checkable
  693. class PR(Protocol):
  694. def meth(self): pass
  695. class NonP(P):
  696. x = 1
  697. class NonPR(PR): pass
  698. class C(object):
  699. x = 1
  700. class D(object):
  701. def meth(self): pass
  702. self.assertNotIsInstance(C(), NonP)
  703. self.assertNotIsInstance(D(), NonPR)
  704. self.assertNotIsSubclass(C, NonP)
  705. self.assertNotIsSubclass(D, NonPR)
  706. self.assertIsInstance(NonPR(), PR)
  707. self.assertIsSubclass(NonPR, PR)
  708. def test_custom_subclasshook(self):
  709. class P(Protocol):
  710. x = 1
  711. class OKClass(object): pass
  712. class BadClass(object):
  713. x = 1
  714. class C(P):
  715. @classmethod
  716. def __subclasshook__(cls, other):
  717. return other.__name__.startswith("OK")
  718. self.assertIsInstance(OKClass(), C)
  719. self.assertNotIsInstance(BadClass(), C)
  720. self.assertIsSubclass(OKClass, C)
  721. self.assertNotIsSubclass(BadClass, C)
  722. def test_issubclass_fails_correctly(self):
  723. @runtime_checkable
  724. class P(Protocol):
  725. x = 1
  726. class C: pass
  727. with self.assertRaises(TypeError):
  728. issubclass(C(), P)
  729. def test_defining_generic_protocols(self):
  730. T = typing.TypeVar('T')
  731. S = typing.TypeVar('S')
  732. @runtime_checkable
  733. class PR(Protocol[T, S]):
  734. def meth(self): pass
  735. class P(PR[int, T], Protocol[T]):
  736. y = 1
  737. self.assertIsSubclass(PR[int, T], PR)
  738. self.assertIsSubclass(P[str], PR)
  739. with self.assertRaises(TypeError):
  740. PR[int]
  741. with self.assertRaises(TypeError):
  742. P[int, str]
  743. with self.assertRaises(TypeError):
  744. PR[int, 1]
  745. with self.assertRaises(TypeError):
  746. PR[int, ClassVar]
  747. class C(PR[int, T]): pass
  748. self.assertIsInstance(C[str](), C)
  749. def test_defining_generic_protocols_old_style(self):
  750. T = typing.TypeVar('T')
  751. S = typing.TypeVar('S')
  752. @runtime_checkable
  753. class PR(Protocol, typing.Generic[T, S]):
  754. def meth(self): pass
  755. class P(PR[int, str], Protocol):
  756. y = 1
  757. self.assertIsSubclass(PR[int, str], PR)
  758. self.assertIsSubclass(P, PR)
  759. with self.assertRaises(TypeError):
  760. PR[int]
  761. with self.assertRaises(TypeError):
  762. PR[int, 1]
  763. class P1(Protocol, typing.Generic[T]):
  764. def bar(self, x): pass
  765. class P2(typing.Generic[T], Protocol):
  766. def bar(self, x): pass
  767. @runtime_checkable
  768. class PSub(P1[str], Protocol):
  769. x = 1
  770. class Test(object):
  771. x = 1
  772. def bar(self, x):
  773. return x
  774. self.assertIsInstance(Test(), PSub)
  775. with self.assertRaises(TypeError):
  776. PR[int, ClassVar]
  777. def test_init_called(self):
  778. T = typing.TypeVar('T')
  779. class P(Protocol[T]): pass
  780. class C(P[T]):
  781. def __init__(self):
  782. self.test = 'OK'
  783. self.assertEqual(C[int]().test, 'OK')
  784. def test_protocols_bad_subscripts(self):
  785. T = typing.TypeVar('T')
  786. S = typing.TypeVar('S')
  787. with self.assertRaises(TypeError):
  788. class P(Protocol[T, T]): pass
  789. with self.assertRaises(TypeError):
  790. class P(Protocol[int]): pass
  791. with self.assertRaises(TypeError):
  792. class P(Protocol[T], Protocol[S]): pass
  793. with self.assertRaises(TypeError):
  794. class P(Protocol[T], typing.Mapping[T, S]): pass
  795. def test_generic_protocols_repr(self):
  796. T = typing.TypeVar('T')
  797. S = typing.TypeVar('S')
  798. class P(Protocol[T, S]): pass
  799. self.assertTrue(repr(P).endswith('P'))
  800. self.assertTrue(repr(P[T, S]).endswith('P[~T, ~S]'))
  801. self.assertTrue(repr(P[int, str]).endswith('P[int, str]'))
  802. def test_generic_protocols_eq(self):
  803. T = typing.TypeVar('T')
  804. S = typing.TypeVar('S')
  805. class P(Protocol[T, S]): pass
  806. self.assertEqual(P, P)
  807. self.assertEqual(P[int, T], P[int, T])
  808. self.assertEqual(P[T, T][typing.Tuple[T, S]][int, str],
  809. P[typing.Tuple[int, str], typing.Tuple[int, str]])
  810. def test_generic_protocols_special_from_generic(self):
  811. T = typing.TypeVar('T')
  812. class P(Protocol[T]): pass
  813. self.assertEqual(P.__parameters__, (T,))
  814. self.assertIs(P.__args__, None)
  815. self.assertIs(P.__origin__, None)
  816. self.assertEqual(P[int].__parameters__, ())
  817. self.assertEqual(P[int].__args__, (int,))
  818. self.assertIs(P[int].__origin__, P)
  819. def test_generic_protocols_special_from_protocol(self):
  820. @runtime_checkable
  821. class PR(Protocol):
  822. x = 1
  823. class P(Protocol):
  824. def meth(self):
  825. pass
  826. T = typing.TypeVar('T')
  827. class PG(Protocol[T]):
  828. x = 1
  829. def meth(self):
  830. pass
  831. self.assertTrue(P._is_protocol)
  832. self.assertTrue(PR._is_protocol)
  833. self.assertTrue(PG._is_protocol)
  834. with self.assertRaises(AttributeError):
  835. self.assertFalse(P._is_runtime_protocol)
  836. self.assertTrue(PR._is_runtime_protocol)
  837. self.assertTrue(PG[int]._is_protocol)
  838. self.assertEqual(P._get_protocol_attrs(), {'meth'})
  839. self.assertEqual(PR._get_protocol_attrs(), {'x'})
  840. self.assertEqual(frozenset(PG._get_protocol_attrs()),
  841. frozenset({'x', 'meth'}))
  842. self.assertEqual(frozenset(PG[int]._get_protocol_attrs()),
  843. frozenset({'x', 'meth'}))
  844. def test_no_runtime_deco_on_nominal(self):
  845. with self.assertRaises(TypeError):
  846. @runtime_checkable
  847. class C(object): pass
  848. class Proto(Protocol):
  849. x = 1
  850. with self.assertRaises(TypeError):
  851. @runtime_checkable
  852. class Concrete(Proto):
  853. pass
  854. def test_none_treated_correctly(self):
  855. @runtime_checkable
  856. class P(Protocol):
  857. x = None # type: int
  858. class B(object): pass
  859. self.assertNotIsInstance(B(), P)
  860. class C(object):
  861. x = 1
  862. class D(object):
  863. x = None
  864. self.assertIsInstance(C(), P)
  865. self.assertIsInstance(D(), P)
  866. class CI(object):
  867. def __init__(self):
  868. self.x = 1
  869. class DI(object):
  870. def __init__(self):
  871. self.x = None
  872. self.assertIsInstance(C(), P)
  873. self.assertIsInstance(D(), P)
  874. def test_protocols_in_unions(self):
  875. class P(Protocol):
  876. x = None # type: int
  877. Alias = typing.Union[typing.Iterable, P]
  878. Alias2 = typing.Union[P, typing.Iterable]
  879. self.assertEqual(Alias, Alias2)
  880. def test_protocols_pickleable(self):
  881. global P, CP # pickle wants to reference the class by name
  882. T = typing.TypeVar('T')
  883. @runtime_checkable
  884. class P(Protocol[T]):
  885. x = 1
  886. class CP(P[int]):
  887. pass
  888. c = CP()
  889. c.foo = 42
  890. c.bar = 'abc'
  891. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  892. z = pickle.dumps(c, proto)
  893. x = pickle.loads(z)
  894. self.assertEqual(x.foo, 42)
  895. self.assertEqual(x.bar, 'abc')
  896. self.assertEqual(x.x, 1)
  897. self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
  898. s = pickle.dumps(P)
  899. D = pickle.loads(s)
  900. class E(object):
  901. x = 1
  902. self.assertIsInstance(E(), D)
  903. def test_supports_int(self):
  904. self.assertIsSubclass(int, typing.SupportsInt)
  905. self.assertNotIsSubclass(str, typing.SupportsInt)
  906. def test_supports_float(self):
  907. self.assertIsSubclass(float, typing.SupportsFloat)
  908. self.assertNotIsSubclass(str, typing.SupportsFloat)
  909. def test_supports_complex(self):
  910. # Note: complex itself doesn't have __complex__.
  911. class C(object):
  912. def __complex__(self):
  913. return 0j
  914. self.assertIsSubclass(C, typing.SupportsComplex)
  915. self.assertNotIsSubclass(str, typing.SupportsComplex)
  916. def test_supports_abs(self):
  917. self.assertIsSubclass(float, typing.SupportsAbs)
  918. self.assertIsSubclass(int, typing.SupportsAbs)
  919. self.assertNotIsSubclass(str, typing.SupportsAbs)
  920. def test_reversible(self):
  921. self.assertIsSubclass(list, typing.Reversible)
  922. self.assertNotIsSubclass(int, typing.Reversible)
  923. def test_supports_index(self):
  924. self.assertIsSubclass(int, typing.SupportsIndex)
  925. self.assertNotIsSubclass(str, typing.SupportsIndex)
  926. def test_protocol_instance_works(self):
  927. self.assertIsInstance(0, typing.SupportsAbs)
  928. self.assertNotIsInstance('no', typing.SupportsAbs)
  929. class C1(typing.SupportsInt):
  930. def __int__(self):
  931. return 42
  932. class C2(C1):
  933. pass
  934. c = C2()
  935. self.assertIsInstance(c, C1)
  936. def test_collections_protocols_allowed(self):
  937. @runtime_checkable
  938. class Custom(collections.Iterable, Protocol):
  939. def close(self): pass
  940. class A(object): pass
  941. class B(object):
  942. def __iter__(self):
  943. return []
  944. def close(self):
  945. return 0
  946. self.assertIsSubclass(B, Custom)
  947. self.assertNotIsSubclass(A, Custom)
  948. class GenericTests(BaseTestCase):
  949. def test_basics(self):
  950. X = SimpleMapping[str, Any]
  951. self.assertEqual(X.__parameters__, ())
  952. with self.assertRaises(TypeError):
  953. X[unicode]
  954. with self.assertRaises(TypeError):
  955. X[unicode, unicode]
  956. Y = SimpleMapping[XK, unicode]
  957. self.assertEqual(Y.__parameters__, (XK,))
  958. Y[unicode]
  959. with self.assertRaises(TypeError):
  960. Y[unicode, unicode]
  961. self.assertIsSubclass(SimpleMapping[str, int], SimpleMapping)
  962. def test_generic_errors(self):
  963. T = TypeVar('T')
  964. S = TypeVar('S')
  965. with self.assertRaises(TypeError):
  966. Generic[T]()
  967. with self.assertRaises(TypeError):
  968. Generic[T][T]
  969. with self.assertRaises(TypeError):
  970. Generic[T][S]
  971. with self.assertRaises(TypeError):
  972. isinstance([], List[int])
  973. with self.assertRaises(TypeError):
  974. issubclass(list, List[int])
  975. with self.assertRaises(TypeError):
  976. class NewGeneric(Generic): pass
  977. with self.assertRaises(TypeError):
  978. class MyGeneric(Generic[T], Generic[S]): pass
  979. with self.assertRaises(TypeError):
  980. class MyGeneric(List[T], Generic[S]): pass
  981. def test_init(self):
  982. T = TypeVar('T')
  983. S = TypeVar('S')
  984. with self.assertRaises(TypeError):
  985. Generic[T, T]
  986. with self.assertRaises(TypeError):
  987. Generic[T, S, T]
  988. def test_repr(self):
  989. self.assertEqual(repr(SimpleMapping),
  990. __name__ + '.' + 'SimpleMapping')
  991. self.assertEqual(repr(MySimpleMapping),
  992. __name__ + '.' + 'MySimpleMapping')
  993. def test_chain_repr(self):
  994. T = TypeVar('T')
  995. S = TypeVar('S')
  996. class C(Generic[T]):
  997. pass
  998. X = C[Tuple[S, T]]
  999. self.assertEqual(X, C[Tuple[S, T]])
  1000. self.assertNotEqual(X, C[Tuple[T, S]])
  1001. Y = X[T, int]
  1002. self.assertEqual(Y, X[T, int])
  1003. self.assertNotEqual(Y, X[S, int])
  1004. self.assertNotEqual(Y, X[T, str])
  1005. Z = Y[str]
  1006. self.assertEqual(Z, Y[str])
  1007. self.assertNotEqual(Z, Y[int])
  1008. self.assertNotEqual(Z, Y[T])
  1009. self.assertTrue(str(Z).endswith(
  1010. '.C[typing.Tuple[str, int]]'))
  1011. def test_new_repr(self):
  1012. T = TypeVar('T')
  1013. U = TypeVar('U', covariant=True)
  1014. S = TypeVar('S')
  1015. self.assertEqual(repr(List), 'typing.List')
  1016. self.assertEqual(repr(List[T]), 'typing.List[~T]')
  1017. self.assertEqual(repr(List[U]), 'typing.List[+U]')
  1018. self.assertEqual(repr(List[S][T][int]), 'typing.List[int]')
  1019. self.assertEqual(repr(List[int]), 'typing.List[int]')
  1020. def test_new_repr_complex(self):
  1021. T = TypeVar('T')
  1022. TS = TypeVar('TS')
  1023. self.assertEqual(repr(typing.Mapping[T, TS][TS, T]), 'typing.Mapping[~TS, ~T]')
  1024. self.assertEqual(repr(List[Tuple[T, TS]][int, T]),
  1025. 'typing.List[typing.Tuple[int, ~T]]')
  1026. self.assertEqual(
  1027. repr(List[Tuple[T, T]][List[int]]),
  1028. 'typing.List[typing.Tuple[typing.List[int], typing.List[int]]]'
  1029. )
  1030. def test_new_repr_bare(self):
  1031. T = TypeVar('T')
  1032. self.assertEqual(repr(Generic[T]), 'typing.Generic[~T]')
  1033. self.assertEqual(repr(typing.Protocol[T]), 'typing.Protocol[~T]')
  1034. class C(typing.Dict[Any, Any]): pass
  1035. # this line should just work
  1036. repr(C.__mro__)
  1037. def test_dict(self):
  1038. T = TypeVar('T')
  1039. class B(Generic[T]):
  1040. pass
  1041. b = B()
  1042. b.foo = 42
  1043. self.assertEqual(b.__dict__, {'foo': 42})
  1044. class C(B[int]):
  1045. pass
  1046. c = C()
  1047. c.bar = 'abc'
  1048. self.assertEqual(c.__dict__, {'bar': 'abc'})
  1049. def test_subscripted_generics_as_proxies(self):
  1050. T = TypeVar('T')
  1051. class C(Generic[T]):
  1052. x = 'def'
  1053. self.assertEqual(C[int].x, 'def')
  1054. self.assertEqual(C[C[int]].x, 'def')
  1055. C[C[int]].x = 'changed'
  1056. self.assertEqual(C.x, 'changed')
  1057. self.assertEqual(C[str].x, 'changed')
  1058. C[List[str]].z = 'new'
  1059. self.assertEqual(C.z, 'new')
  1060. self.assertEqual(C[Tuple[int]].z, 'new')
  1061. self.assertEqual(C().x, 'changed')
  1062. self.assertEqual(C[Tuple[str]]().z, 'new')
  1063. class D(C[T]):
  1064. pass
  1065. self.assertEqual(D[int].x, 'changed')
  1066. self.assertEqual(D.z, 'new')
  1067. D.z = 'from derived z'
  1068. D[int].x = 'from derived x'
  1069. self.assertEqual(C.x, 'changed')
  1070. self.assertEqual(C[int].z, 'new')
  1071. self.assertEqual(D.x, 'from derived x')
  1072. self.assertEqual(D[str].z, 'from derived z')
  1073. def test_abc_registry_kept(self):
  1074. T = TypeVar('T')
  1075. class C(Generic[T]): pass
  1076. C.register(int)
  1077. self.assertIsInstance(1, C)
  1078. C[int]
  1079. self.assertIsInstance(1, C)
  1080. def test_false_subclasses(self):
  1081. class MyMapping(MutableMapping[str, str]): pass
  1082. self.assertNotIsInstance({}, MyMapping)
  1083. self.assertNotIsSubclass(dict, MyMapping)
  1084. def test_abc_bases(self):
  1085. class MM(MutableMapping[str, str]):
  1086. def __getitem__(self, k):
  1087. return None
  1088. def __setitem__(self, k, v):
  1089. pass
  1090. def __delitem__(self, k):
  1091. pass
  1092. def __iter__(self):
  1093. return iter(())
  1094. def __len__(self):
  1095. return 0
  1096. # this should just work
  1097. MM().update()
  1098. self.assertIsInstance(MM(), collections.MutableMapping)
  1099. self.assertIsInstance(MM(), MutableMapping)
  1100. self.assertNotIsInstance(MM(), List)
  1101. self.assertNotIsInstance({}, MM)
  1102. def test_multiple_bases(self):
  1103. class MM1(MutableMapping[str, str], collections.MutableMapping):
  1104. pass
  1105. with self.assertRaises(TypeError):
  1106. # consistent MRO not possible
  1107. class MM2(collections.MutableMapping, MutableMapping[str, str]):
  1108. pass
  1109. def test_orig_bases(self):
  1110. T = TypeVar('T')
  1111. class C(typing.Dict[str, T]): pass
  1112. self.assertEqual(C.__orig_bases__, (typing.Dict[str, T],))
  1113. def test_naive_runtime_checks(self):
  1114. def naive_dict_check(obj, tp):
  1115. # Check if a dictionary conforms to Dict type
  1116. if len(tp.__parameters__) > 0:
  1117. raise NotImplementedError
  1118. if tp.__args__:
  1119. KT, VT = tp.__args__
  1120. return all(
  1121. isinstance(k, KT) and isinstance(v, VT)
  1122. for k, v in obj.items()
  1123. )
  1124. self.assertTrue(naive_dict_check({'x': 1}, typing.Dict[typing.Text, int]))
  1125. self.assertFalse(naive_dict_check({1: 'x'}, typing.Dict[typing.Text, int]))
  1126. with self.assertRaises(NotImplementedError):
  1127. naive_dict_check({1: 'x'}, typing.Dict[typing.Text, T])
  1128. def naive_generic_check(obj, tp):
  1129. # Check if an instance conforms to the generic class
  1130. if not hasattr(obj, '__orig_class__'):
  1131. raise NotImplementedError
  1132. return obj.__orig_class__ == tp
  1133. class Node(Generic[T]): pass
  1134. self.assertTrue(naive_generic_check(Node[int](), Node[int]))
  1135. self.assertFalse(naive_generic_check(Node[str](), Node[int]))
  1136. self.assertFalse(naive_generic_check(Node[str](), List))
  1137. with self.assertRaises(NotImplementedError):
  1138. naive_generic_check([1, 2, 3], Node[int])
  1139. def naive_list_base_check(obj, tp):
  1140. # Check if list conforms to a List subclass
  1141. return all(isinstance(x, tp.__orig_bases__[0].__args__[0])
  1142. for x in obj)
  1143. class C(List[int]): pass
  1144. self.assertTrue(naive_list_base_check([1, 2, 3], C))
  1145. self.assertFalse(naive_list_base_check(['a', 'b'], C))
  1146. def test_multi_subscr_base(self):
  1147. T = TypeVar('T')
  1148. U = TypeVar('U')
  1149. V = TypeVar('V')
  1150. class C(List[T][U][V]): pass
  1151. class D(C, List[T][U][V]): pass
  1152. self.assertEqual(C.__parameters__, (V,))
  1153. self.assertEqual(D.__parameters__, (V,))
  1154. self.assertEqual(C[int].__parameters__, ())
  1155. self.assertEqual(D[int].__parameters__, ())
  1156. self.assertEqual(C[int].__args__, (int,))
  1157. self.assertEqual(D[int].__args__, (int,))
  1158. self.assertEqual(C.__bases__, (List,))
  1159. self.assertEqual(D.__bases__, (C, List))
  1160. self.assertEqual(C.__orig_bases__, (List[T][U][V],))
  1161. self.assertEqual(D.__orig_bases__, (C, List[T][U][V]))
  1162. def test_subscript_meta(self):
  1163. T = TypeVar('T')
  1164. self.assertEqual(Type[GenericMeta], Type[GenericMeta])
  1165. self.assertEqual(Union[T, int][GenericMeta], Union[GenericMeta, int])
  1166. self.assertEqual(Callable[..., GenericMeta].__args__, (Ellipsis, GenericMeta))
  1167. def test_generic_hashes(self):
  1168. import mod_generics_cache
  1169. class A(Generic[T]):
  1170. __module__ = 'test_typing'
  1171. class B(Generic[T]):
  1172. class A(Generic[T]):
  1173. pass
  1174. self.assertEqual(A, A)
  1175. self.assertEqual(mod_generics_cache.A[str], mod_generics_cache.A[str])
  1176. self.assertEqual(B.A, B.A)
  1177. self.assertEqual(mod_generics_cache.B.A[B.A[str]],
  1178. mod_generics_cache.B.A[B.A[str]])
  1179. self.assertNotEqual(A, B.A)
  1180. self.assertNotEqual(A, mod_generics_cache.A)
  1181. self.assertNotEqual(A, mod_generics_cache.B.A)
  1182. self.assertNotEqual(B.A, mod_generics_cache.A)
  1183. self.assertNotEqual(B.A, mod_generics_cache.B.A)
  1184. self.assertNotEqual(A[str], B.A[str])
  1185. self.assertNotEqual(A[List[Any]], B.A[List[Any]])
  1186. self.assertNotEqual(A[str], mod_generics_cache.A[str])
  1187. self.assertNotEqual(A[str], mod_generics_cache.B.A[str])
  1188. self.assertNotEqual(B.A[int], mod_generics_cache.A[int])
  1189. self.assertNotEqual(B.A[List[Any]], mod_generics_cache.B.A[List[Any]])
  1190. self.assertNotEqual(Tuple[A[str]], Tuple[B.A[str]])
  1191. self.assertNotEqual(Tuple[A[List[Any]]], Tuple[B.A[List[Any]]])
  1192. self.assertNotEqual(Union[str, A[str]], Union[str, mod_generics_cache.A[str]])
  1193. self.assertNotEqual(Union[A[str], A[str]],
  1194. Union[A[str], mod_generics_cache.A[str]])
  1195. self.assertNotEqual(typing.FrozenSet[A[str]],
  1196. typing.FrozenSet[mod_generics_cache.B.A[str]])
  1197. self.assertTrue(repr(Tuple[A[str]]).endswith('test_typing.A[str]]'))
  1198. self.assertTrue(repr(Tuple[mod_generics_cache.A[str]])
  1199. .endswith('mod_generics_cache.A[str]]'))
  1200. def test_extended_generic_rules_eq(self):
  1201. T = TypeVar('T')
  1202. U = TypeVar('U')
  1203. self.assertEqual(Tuple[T, T][int], Tuple[int, int])
  1204. self.assertEqual(typing.Iterable[Tuple[T, T]][T], typing.Iterable[Tuple[T, T]])
  1205. with self.assertRaises(TypeError):
  1206. Tuple[T, int][()]
  1207. with self.assertRaises(TypeError):
  1208. Tuple[T, U][T, ...]
  1209. self.assertEqual(Union[T, int][int], int)
  1210. self.assertEqual(Union[T, U][int, Union[int, str]], Union[int, str])
  1211. class Base(object): pass
  1212. class Derived(Base): pass
  1213. self.assertEqual(Union[T, Base][Derived], Base)
  1214. with self.assertRaises(TypeError):
  1215. Union[T, int][1]
  1216. self.assertEqual(Callable[[T], T][KT], Callable[[KT], KT])
  1217. self.assertEqual(Callable[..., List[T]][int], Callable[..., List[int]])
  1218. with self.assertRaises(TypeError):
  1219. Callable[[T], U][..., int]
  1220. with self.assertRaises(TypeError):
  1221. Callable[[T], U][[], int]
  1222. def test_extended_generic_rules_repr(self):
  1223. T = TypeVar('T')
  1224. self.assertEqual(repr(Union[Tuple, Callable]).replace('typing.', ''),
  1225. 'Union[Tuple, Callable]')
  1226. self.assertEqual(repr(Union[Tuple, Tuple[int]]).replace('typing.', ''),
  1227. 'Tuple')
  1228. self.assertEqual(repr(Callable[..., Optional[T]][int]).replace('typing.', ''),
  1229. 'Callable[..., Union[int, NoneType]]')
  1230. self.assertEqual(repr(Callable[[], List[T]][int]).replace('typing.', ''),
  1231. 'Callable[[], List[int]]')
  1232. def test_generic_forvard_ref(self):
  1233. LLT = List[List['CC']]
  1234. class CC: pass
  1235. self.assertEqual(typing._eval_type(LLT, globals(), locals()), List[List[CC]])
  1236. T = TypeVar('T')
  1237. AT = Tuple[T, ...]
  1238. self.assertIs(typing._eval_type(AT, globals(), locals()), AT)
  1239. CT = Callable[..., List[T]]
  1240. self.assertIs(typing._eval_type(CT, globals(), locals()), CT)
  1241. def test_extended_generic_rules_subclassing(self):
  1242. class T1(Tuple[T, KT]): pass
  1243. class T2(Tuple[T, ...]): pass
  1244. class C1(Callable[[T], T]): pass
  1245. class C2(Callable[..., int]):
  1246. def __call__(self):
  1247. return None
  1248. self.assertEqual(T1.__parameters__, (T, KT))
  1249. self.assertEqual(T1[int, str].__args__, (int, str))
  1250. self.assertEqual(T1[int, T].__origin__, T1)
  1251. self.assertEqual(T2.__parameters__, (T,))
  1252. with self.assertRaises(TypeError):
  1253. T1[int]
  1254. with self.assertRaises(TypeError):
  1255. T2[int, str]
  1256. self.assertEqual(repr(C1[int]).split('.')[-1], 'C1[int]')
  1257. self.assertEqual(C2.__parameters__, ())
  1258. self.assertIsInstance(C2(), collections.Callable)
  1259. self.assertIsSubclass(C2, collections.Callable)
  1260. self.assertIsSubclass(C1, collections.Callable)
  1261. self.assertIsInstance(T1(), tuple)
  1262. self.assertIsSubclass(T2, tuple)
  1263. self.assertIsSubclass(Tuple[int, ...], typing.Sequence)
  1264. self.assertIsSubclass(Tuple[int, ...], typing.Iterable)
  1265. def test_fail_with_bare_union(self):
  1266. with self.assertRaises(TypeError):
  1267. List[Union]
  1268. with self.assertRaises(TypeError):
  1269. Tuple[Optional]
  1270. with self.assertRaises(TypeError):
  1271. ClassVar[ClassVar]
  1272. with self.assertRaises(TypeError):
  1273. List[ClassVar[int]]
  1274. def test_fail_with_bare_generic(self):
  1275. T = TypeVar('T')
  1276. with self.assertRaises(TypeError):
  1277. List[Generic]
  1278. with self.assertRaises(TypeError):
  1279. Tuple[Generic[T]]
  1280. with self.assertRaises(TypeError):
  1281. List[typing.Protocol]
  1282. with self.assertRaises(TypeError):
  1283. isinstance(1, Generic)
  1284. def test_type_erasure_special(self):
  1285. T = TypeVar('T')
  1286. # this is the only test that checks type caching
  1287. self.clear_caches()
  1288. class MyTup(Tuple[T, T]): pass
  1289. self.assertIs(MyTup[int]().__class__, MyTup)
  1290. self.assertIs(MyTup[int]().__orig_class__, MyTup[int])
  1291. class MyCall(Callable[..., T]):
  1292. def __call__(self): return None
  1293. self.assertIs(MyCall[T]().__class__, MyCall)
  1294. self.assertIs(MyCall[T]().__orig_class__, MyCall[T])
  1295. class MyDict(typing.Dict[T, T]): pass
  1296. self.assertIs(MyDict[int]().__class__, MyDict)
  1297. self.assertIs(MyDict[int]().__orig_class__, MyDict[int])
  1298. class MyDef(typing.DefaultDict[str, T]): pass
  1299. self.assertIs(MyDef[int]().__class__, MyDef)
  1300. self.assertIs(MyDef[int]().__orig_class__, MyDef[int])
  1301. def test_all_repr_eq_any(self):
  1302. objs = (getattr(typing, el) for el in typing.__all__)
  1303. for obj in objs:
  1304. self.assertNotEqual(repr(obj), '')
  1305. self.assertEqual(obj, obj)
  1306. if getattr(obj, '__parameters__', None) and len(obj.__parameters__) == 1:
  1307. self.assertEqual(obj[Any].__args__, (Any,))
  1308. if isinstance(obj, type):
  1309. for base in obj.__mro__:
  1310. self.assertNotEqual(repr(base), '')
  1311. self.assertEqual(base, base)
  1312. def test_pickle(self):
  1313. global C # pickle wants to reference the class by name
  1314. T = TypeVar('T')
  1315. class B(Generic[T]):
  1316. pass
  1317. class C(B[int]):
  1318. pass
  1319. c = C()
  1320. c.foo = 42
  1321. c.bar = 'abc'
  1322. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  1323. z = pickle.dumps(c, proto)
  1324. x = pickle.loads(z)
  1325. self.assertEqual(x.foo, 42)
  1326. self.assertEqual(x.bar, 'abc')
  1327. self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
  1328. simples = [Any, Union, Tuple, Callable, ClassVar, List, typing.Iterable]
  1329. for s in simples:
  1330. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  1331. z = pickle.dumps(s, proto)
  1332. x = pickle.loads(z)
  1333. self.assertEqual(s, x)
  1334. def test_copy_and_deepcopy(self):
  1335. T = TypeVar('T')
  1336. class Node(Generic[T]): pass
  1337. things = [
  1338. Any,
  1339. Callable[..., T],
  1340. Callable[[int], int],
  1341. ClassVar[List[T]],
  1342. ClassVar[int],
  1343. List['T'],
  1344. Node[Any],
  1345. Node[T],
  1346. Node[int],
  1347. Tuple['T', 'T'],
  1348. Tuple[Any, Any],
  1349. Tuple[T, int],
  1350. Union['T', int],
  1351. Union[T, int],
  1352. typing.Dict[T, Any],
  1353. typing.Dict[int, str],
  1354. typing.Iterable[Any],
  1355. typing.Iterable[T],
  1356. typing.Iterable[int],
  1357. typing.Mapping['T', int]
  1358. ]
  1359. for t in things:
  1360. self.assertEqual(t, deepcopy(t))
  1361. self.assertEqual(t, copy(t))
  1362. def test_copy_generic_instances(self):
  1363. T = TypeVar('T')
  1364. class C(Generic[T]):
  1365. def __init__(self, attr):
  1366. self.attr = attr
  1367. c = C(42)
  1368. self.assertEqual(copy(c).attr, 42)
  1369. self.assertEqual(deepcopy(c).attr, 42)
  1370. self.assertIsNot(copy(c), c)
  1371. self.assertIsNot(deepcopy(c), c)
  1372. c.attr = 1
  1373. self.assertEqual(copy(c).attr, 1)
  1374. self.assertEqual(deepcopy(c).attr, 1)
  1375. ci = C[int](42)
  1376. self.assertEqual(copy(ci).attr, 42)
  1377. self.assertEqual(deepcopy(ci).attr, 42)
  1378. self.assertIsNot(copy(ci), ci)
  1379. self.assertIsNot(deepcopy(ci), ci)
  1380. ci.attr = 1
  1381. self.assertEqual(copy(ci).attr, 1)
  1382. self.assertEqual(deepcopy(ci).attr, 1)
  1383. self.assertEqual(ci.__orig_class__, C[int])
  1384. def test_weakref_all(self):
  1385. T = TypeVar('T')
  1386. things = [Any, Union[T, int], Callable[..., T], Tuple[Any, Any],
  1387. Optional[List[int]], typing.Mapping[int, str],
  1388. typing.re.Match[bytes], typing.Iterable['whatever']]
  1389. for t in things:
  1390. self.assertEqual(weakref.ref(t)(), t)
  1391. def test_parameterized_slots(self):
  1392. T = TypeVar('T')
  1393. class C(Generic[T]):
  1394. __slots__ = ('potato',)
  1395. c = C()
  1396. c_int = C[int]()
  1397. self.assertEqual(C.__slots__, C[str].__slots__)
  1398. c.potato = 0
  1399. c_int.potato = 0
  1400. with self.assertRaises(AttributeError):
  1401. c.tomato = 0
  1402. with self.assertRaises(AttributeError):
  1403. c_int.tomato = 0
  1404. self.assertEqual(typing._eval_type(C['C'], globals(), locals()), C[C])
  1405. self.assertEqual(typing._eval_type(C['C'], globals(), locals()).__slots__,
  1406. C.__slots__)
  1407. self.assertEqual(copy(C[int]), deepcopy(C[int]))
  1408. def test_parameterized_slots_dict(self):
  1409. T = TypeVar('T')
  1410. class D(Generic[T]):
  1411. __slots__ = {'banana': 42}
  1412. d = D()
  1413. d_int = D[int]()
  1414. self.assertEqual(D.__slots__, D[str].__slots__)
  1415. d.banana = 'yes'
  1416. d_int.banana = 'yes'
  1417. with self.assertRaises(AttributeError):
  1418. d.foobar = 'no'
  1419. with self.assertRaises(AttributeError):
  1420. d_int.foobar = 'no'
  1421. def test_errors(self):
  1422. with self.assertRaises(TypeError):
  1423. B = SimpleMapping[XK, Any]
  1424. class C(Generic[B]):
  1425. pass
  1426. def test_repr_2(self):
  1427. PY32 = sys.version_info[:2] < (3, 3)
  1428. class C(Generic[T]):
  1429. pass
  1430. self.assertEqual(C.__module__, __name__)
  1431. if not PY32:
  1432. self.assertEqual(C.__qualname__,
  1433. 'GenericTests.test_repr_2.<locals>.C')
  1434. self.assertEqual(repr(C).split('.')[-1], 'C')
  1435. X = C[int]
  1436. self.assertEqual(X.__module__, __name__)
  1437. if not PY32:
  1438. self.assertTrue(X.__qualname__.endswith('.<locals>.C'))
  1439. self.assertEqual(repr(X).split('.')[-1], 'C[int]')
  1440. class Y(C[int]):
  1441. pass
  1442. self.assertEqual(Y.__module__, __name__)
  1443. if not PY32:
  1444. self.assertEqual(Y.__qualname__,
  1445. 'GenericTests.test_repr_2.<locals>.Y')
  1446. self.assertEqual(repr(Y).split('.')[-1], 'Y')
  1447. def test_eq_1(self):
  1448. self.assertEqual(Generic, Generic)
  1449. self.assertEqual(Generic[T], Generic[T])
  1450. self.assertNotEqual(Generic[KT], Generic[VT])
  1451. def test_eq_2(self):
  1452. class A(Generic[T]):
  1453. pass
  1454. class B(Generic[T]):
  1455. pass
  1456. self.assertEqual(A, A)
  1457. self.assertNotEqual(A, B)
  1458. self.assertEqual(A[T], A[T])
  1459. self.assertNotEqual(A[T], B[T])
  1460. def test_multiple_inheritance(self):
  1461. class A(Generic[T, VT]):
  1462. pass
  1463. class B(Generic[KT, T]):
  1464. pass
  1465. class C(A[T, VT], Generic[VT, T, KT], B[KT, T]):
  1466. pass
  1467. self.assertEqual(C.__parameters__, (VT, T, KT))
  1468. def test_nested(self):
  1469. G = Generic
  1470. class Visitor(G[T]):
  1471. a = None
  1472. def set(self, a):
  1473. self.a = a
  1474. def get(self):
  1475. return self.a
  1476. def visit(self):
  1477. return self.a
  1478. V = Visitor[typing.List[int]]
  1479. class IntListVisitor(V):
  1480. def append(self, x):
  1481. self.a.append(x)
  1482. a = IntListVisitor()
  1483. a.set([])
  1484. a.append(1)
  1485. a.append(42)
  1486. self.assertEqual(a.get(), [1, 42])
  1487. def test_type_erasure(self):
  1488. T = TypeVar('T')
  1489. class Node(Generic[T]):
  1490. def __init__(self, label,
  1491. left=None,
  1492. right=None):
  1493. self.label = label # type: T
  1494. self.left = left # type: Optional[Node[T]]
  1495. self.right = right # type: Optional[Node[T]]
  1496. def foo(x):
  1497. a = Node(x)
  1498. b = Node[T](x)
  1499. c = Node[Any](x)
  1500. self.assertIs(type(a), Node)
  1501. self.assertIs(type(b), Node)
  1502. self.assertIs(type(c), Node)
  1503. self.assertEqual(a.label, x)
  1504. self.assertEqual(b.label, x)
  1505. self.assertEqual(c.label, x)
  1506. foo(42)
  1507. def test_implicit_any(self):
  1508. T = TypeVar('T')
  1509. class C(Generic[T]):
  1510. pass
  1511. class D(C):
  1512. pass
  1513. self.assertEqual(D.__parameters__, ())
  1514. with self.assertRaises(Exception):
  1515. D[int]
  1516. with self.assertRaises(Exception):
  1517. D[Any]
  1518. with self.assertRaises(Exception):
  1519. D[T]
  1520. def test_new_with_args(self):
  1521. class A(Generic[T]):
  1522. pass
  1523. class B(object):
  1524. def __new__(cls, arg):
  1525. # call object.__new__
  1526. obj = super(B, cls).__new__(cls)
  1527. obj.arg = arg
  1528. return obj
  1529. # mro: C, A, Generic, B, object
  1530. class C(A, B):
  1531. pass
  1532. c = C('foo')
  1533. self.assertEqual(c.arg, 'foo')
  1534. def test_new_with_args2(self):
  1535. class A(object):
  1536. def __init__(self, arg):
  1537. self.from_a = arg
  1538. # call object
  1539. super(A, self).__init__()
  1540. # mro: C, Generic, A, object
  1541. class C(Generic[T], A):
  1542. def __init__(self, arg):
  1543. self.from_c = arg
  1544. # call Generic
  1545. super(C, self).__init__(arg)
  1546. c = C('foo')
  1547. self.assertEqual(c.from_a, 'foo')
  1548. self.assertEqual(c.from_c, 'foo')
  1549. def test_new_no_args(self):
  1550. class A(Generic[T]):
  1551. pass
  1552. with self.assertRaises(TypeError):
  1553. A('foo')
  1554. class B(object):
  1555. def __new__(cls):
  1556. # call object
  1557. obj = super(B, cls).__new__(cls)
  1558. obj.from_b = 'b'
  1559. return obj
  1560. # mro: C, A, Generic, B, object
  1561. class C(A, B):
  1562. def __init__(self, arg):
  1563. self.arg = arg
  1564. def __new__(cls, arg):
  1565. # call A
  1566. obj = super(C, cls).__new__(cls)
  1567. obj.from_c = 'c'
  1568. return obj
  1569. c = C('foo')
  1570. self.assertEqual(c.arg, 'foo')
  1571. self.assertEqual(c.from_b, 'b')
  1572. self.assertEqual(c.from_c, 'c')
  1573. class ClassVarTests(BaseTestCase):
  1574. def test_basics(self):
  1575. with self.assertRaises(TypeError):
  1576. ClassVar[1]
  1577. with self.assertRaises(TypeError):
  1578. ClassVar[int, str]
  1579. with self.assertRaises(TypeError):
  1580. ClassVar[int][str]
  1581. def test_repr(self):
  1582. self.assertEqual(repr(ClassVar), 'typing.ClassVar')
  1583. cv = ClassVar[int]
  1584. self.assertEqual(repr(cv), 'typing.ClassVar[int]')
  1585. cv = ClassVar[Employee]
  1586. self.assertEqual(repr(cv), 'typing.ClassVar[%s.Employee]' % __name__)
  1587. def test_cannot_subclass(self):
  1588. with self.assertRaises(TypeError):
  1589. class C(type(ClassVar)):
  1590. pass
  1591. with self.assertRaises(TypeError):
  1592. class C(type(ClassVar[int])):
  1593. pass
  1594. def test_cannot_init(self):
  1595. with self.assertRaises(TypeError):
  1596. ClassVar()
  1597. with self.assertRaises(TypeError):
  1598. type(ClassVar)()
  1599. with self.assertRaises(TypeError):
  1600. type(ClassVar[Optional[int]])()
  1601. def test_no_isinstance(self):
  1602. with self.assertRaises(TypeError):
  1603. isinstance(1, ClassVar[int])
  1604. with self.assertRaises(TypeError):
  1605. issubclass(int, ClassVar)
  1606. class FinalTests(BaseTestCase):
  1607. def test_basics(self):
  1608. with self.assertRaises(TypeError):
  1609. Final[1]
  1610. with self.assertRaises(TypeError):
  1611. Final[int, str]
  1612. with self.assertRaises(TypeError):
  1613. Final[int][str]
  1614. def test_repr(self):
  1615. self.assertEqual(repr(Final), 'typing.Final')
  1616. cv = Final[int]
  1617. self.assertEqual(repr(cv), 'typing.Final[int]')
  1618. cv = Final[Employee]
  1619. self.assertEqual(repr(cv), 'typing.Final[%s.Employee]' % __name__)
  1620. def test_cannot_subclass(self):
  1621. with self.assertRaises(TypeError):
  1622. class C(type(Final)):
  1623. pass
  1624. with self.assertRaises(TypeError):
  1625. class C(type(Final[int])):
  1626. pass
  1627. def test_cannot_init(self):
  1628. with self.assertRaises(TypeError):
  1629. Final()
  1630. with self.assertRaises(TypeError):
  1631. type(Final)()
  1632. with self.assertRaises(TypeError):
  1633. type(Final[typing.Optional[int]])()
  1634. def test_no_isinstance(self):
  1635. with self.assertRaises(TypeError):
  1636. isinstance(1, Final[int])
  1637. with self.assertRaises(TypeError):
  1638. issubclass(int, Final)
  1639. class LiteralTests(BaseTestCase):
  1640. def test_basics(self):
  1641. Literal[1]
  1642. Literal[1, 2, 3]
  1643. Literal["x", "y", "z"]
  1644. Literal[None]
  1645. def test_illegal_parameters_do_not_raise_runtime_errors(self):
  1646. # Type checkers should reject these types, but we do not
  1647. # raise errors at runtime to maintain maximium flexibility
  1648. Literal[int]
  1649. Literal[Literal[1, 2], Literal[4, 5]]
  1650. Literal[3j + 2, ..., ()]
  1651. Literal[b"foo", u"bar"]
  1652. Literal[{"foo": 3, "bar": 4}]
  1653. Literal[T]
  1654. def test_literals_inside_other_types(self):
  1655. typing.List[Literal[1, 2, 3]]
  1656. typing.List[Literal[("foo", "bar", "baz")]]
  1657. def test_repr(self):
  1658. self.assertEqual(repr(Literal[1]), "typing.Literal[1]")
  1659. self.assertEqual(repr(Literal[1, True, "foo"]), "typing.Literal[1, True, u'foo']")
  1660. self.assertEqual(repr(Literal[int]), "typing.Literal[int]")
  1661. self.assertEqual(repr(Literal), "typing.Literal")
  1662. self.assertEqual(repr(Literal[None]), "typing.Literal[None]")
  1663. def test_cannot_init(self):
  1664. with self.assertRaises(TypeError):
  1665. Literal()
  1666. with self.assertRaises(TypeError):
  1667. Literal[1]()
  1668. with self.assertRaises(TypeError):
  1669. type(Literal)()
  1670. with self.assertRaises(TypeError):
  1671. type(Literal[1])()
  1672. def test_no_isinstance_or_issubclass(self):
  1673. with self.assertRaises(TypeError):
  1674. isinstance(1, Literal[1])
  1675. with self.assertRaises(TypeError):
  1676. isinstance(int, Literal[1])
  1677. with self.assertRaises(TypeError):
  1678. issubclass(1, Literal[1])
  1679. with self.assertRaises(TypeError):
  1680. issubclass(int, Literal[1])
  1681. def test_no_subclassing(self):
  1682. with self.assertRaises(TypeError):
  1683. class Foo(Literal[1]): pass
  1684. with self.assertRaises(TypeError):
  1685. class Bar(Literal): pass
  1686. def test_no_multiple_subscripts(self):
  1687. with self.assertRaises(TypeError):
  1688. Literal[1][1]
  1689. class CastTests(BaseTestCase):
  1690. def test_basics(self):
  1691. self.assertEqual(cast(int, 42), 42)
  1692. self.assertEqual(cast(float, 42), 42)
  1693. self.assertIs(type(cast(float, 42)), int)
  1694. self.assertEqual(cast(Any, 42), 42)
  1695. self.assertEqual(cast(list, 42), 42)
  1696. self.assertEqual(cast(Union[str, float], 42), 42)
  1697. self.assertEqual(cast(AnyStr, 42), 42)
  1698. self.assertEqual(cast(None, 42), 42)
  1699. def test_errors(self):
  1700. # Bogus calls are not expected to fail.
  1701. cast(42, 42)
  1702. cast('hello', 42)
  1703. class ForwardRefTests(BaseTestCase):
  1704. def test_forwardref_instance_type_error(self):
  1705. fr = typing._ForwardRef('int')
  1706. with self.assertRaises(TypeError):
  1707. isinstance(42, fr)
  1708. def test_syntax_error(self):
  1709. with self.assertRaises(SyntaxError):
  1710. Generic['/T']
  1711. def test_forwardref_subclass_type_error(self):
  1712. fr = typing._ForwardRef('int')
  1713. with self.assertRaises(TypeError):
  1714. issubclass(int, fr)
  1715. def test_forward_equality(self):
  1716. fr = typing._ForwardRef('int')
  1717. self.assertEqual(fr, typing._ForwardRef('int'))
  1718. self.assertNotEqual(List['int'], List[int])
  1719. def test_forward_repr(self):
  1720. self.assertEqual(repr(List['int']), "typing.List[_ForwardRef(%r)]" % 'int')
  1721. class OverloadTests(BaseTestCase):
  1722. def test_overload_fails(self):
  1723. from typing import overload
  1724. with self.assertRaises(RuntimeError):
  1725. @overload
  1726. def blah():
  1727. pass
  1728. blah()
  1729. def test_overload_succeeds(self):
  1730. from typing import overload
  1731. @overload
  1732. def blah():
  1733. pass
  1734. def blah():
  1735. pass
  1736. blah()
  1737. class CollectionsAbcTests(BaseTestCase):
  1738. def test_hashable(self):
  1739. self.assertIsInstance(42, typing.Hashable)
  1740. self.assertNotIsInstance([], typing.Hashable)
  1741. def test_iterable(self):
  1742. self.assertIsInstance([], typing.Iterable)
  1743. # Due to ABC caching, the second time takes a separate code
  1744. # path and could fail. So call this a few times.
  1745. self.assertIsInstance([], typing.Iterable)
  1746. self.assertIsInstance([], typing.Iterable)
  1747. self.assertNotIsInstance(42, typing.Iterable)
  1748. # Just in case, also test issubclass() a few times.
  1749. self.assertIsSubclass(list, typing.Iterable)
  1750. self.assertIsSubclass(list, typing.Iterable)
  1751. def test_iterator(self):
  1752. it = iter([])
  1753. self.assertIsInstance(it, typing.Iterator)
  1754. self.assertNotIsInstance(42, typing.Iterator)
  1755. def test_sized(self):
  1756. self.assertIsInstance([], typing.Sized)
  1757. self.assertNotIsInstance(42, typing.Sized)
  1758. def test_container(self):
  1759. self.assertIsInstance([], typing.Container)
  1760. self.assertNotIsInstance(42, typing.Container)
  1761. def test_abstractset(self):
  1762. self.assertIsInstance(set(), typing.AbstractSet)
  1763. self.assertNotIsInstance(42, typing.AbstractSet)
  1764. def test_mutableset(self):
  1765. self.assertIsInstance(set(), typing.MutableSet)
  1766. self.assertNotIsInstance(frozenset(), typing.MutableSet)
  1767. def test_mapping(self):
  1768. self.assertIsInstance({}, typing.Mapping)
  1769. self.assertNotIsInstance(42, typing.Mapping)
  1770. def test_mutablemapping(self):
  1771. self.assertIsInstance({}, typing.MutableMapping)
  1772. self.assertNotIsInstance(42, typing.MutableMapping)
  1773. def test_sequence(self):
  1774. self.assertIsInstance([], typing.Sequence)
  1775. self.assertNotIsInstance(42, typing.Sequence)
  1776. def test_mutablesequence(self):
  1777. self.assertIsInstance([], typing.MutableSequence)
  1778. self.assertNotIsInstance((), typing.MutableSequence)
  1779. def test_bytestring(self):
  1780. self.assertIsInstance(b'', typing.ByteString)
  1781. self.assertIsInstance(bytearray(b''), typing.ByteString)
  1782. def test_list(self):
  1783. self.assertIsSubclass(list, typing.List)
  1784. def test_deque(self):
  1785. self.assertIsSubclass(collections.deque, typing.Deque)
  1786. class MyDeque(typing.Deque[int]): pass
  1787. self.assertIsInstance(MyDeque(), collections.deque)
  1788. def test_counter(self):
  1789. self.assertIsSubclass(collections.Counter, typing.Counter)
  1790. def test_set(self):
  1791. self.assertIsSubclass(set, typing.Set)
  1792. self.assertNotIsSubclass(frozenset, typing.Set)
  1793. def test_frozenset(self):
  1794. self.assertIsSubclass(frozenset, typing.FrozenSet)
  1795. self.assertNotIsSubclass(set, typing.FrozenSet)
  1796. def test_dict(self):
  1797. self.assertIsSubclass(dict, typing.Dict)
  1798. def test_no_list_instantiation(self):
  1799. with self.assertRaises(TypeError):
  1800. typing.List()
  1801. with self.assertRaises(TypeError):
  1802. typing.List[T]()
  1803. with self.assertRaises(TypeError):
  1804. typing.List[int]()
  1805. def test_list_subclass(self):
  1806. class MyList(typing.List[int]):
  1807. pass
  1808. a = MyList()
  1809. self.assertIsInstance(a, MyList)
  1810. self.assertIsInstance(a, typing.Sequence)
  1811. self.assertIsSubclass(MyList, list)
  1812. self.assertNotIsSubclass(list, MyList)
  1813. def test_no_dict_instantiation(self):
  1814. with self.assertRaises(TypeError):
  1815. typing.Dict()
  1816. with self.assertRaises(TypeError):
  1817. typing.Dict[KT, VT]()
  1818. with self.assertRaises(TypeError):
  1819. typing.Dict[str, int]()
  1820. def test_dict_subclass(self):
  1821. class MyDict(typing.Dict[str, int]):
  1822. pass
  1823. d = MyDict()
  1824. self.assertIsInstance(d, MyDict)
  1825. self.assertIsInstance(d, typing.MutableMapping)
  1826. self.assertIsSubclass(MyDict, dict)
  1827. self.assertNotIsSubclass(dict, MyDict)
  1828. def test_defaultdict_instantiation(self):
  1829. self.assertIs(type(typing.DefaultDict()), collections.defaultdict)
  1830. self.assertIs(type(typing.DefaultDict[KT, VT]()), collections.defaultdict)
  1831. self.assertIs(type(typing.DefaultDict[str, int]()), collections.defaultdict)
  1832. def test_defaultdict_subclass(self):
  1833. class MyDefDict(typing.DefaultDict[str, int]):
  1834. pass
  1835. dd = MyDefDict()
  1836. self.assertIsInstance(dd, MyDefDict)
  1837. self.assertIsSubclass(MyDefDict, collections.defaultdict)
  1838. self.assertNotIsSubclass(collections.defaultdict, MyDefDict)
  1839. def test_deque_instantiation(self):
  1840. self.assertIs(type(typing.Deque()), collections.deque)
  1841. self.assertIs(type(typing.Deque[T]()), collections.deque)
  1842. self.assertIs(type(typing.Deque[int]()), collections.deque)
  1843. class D(typing.Deque[T]): pass
  1844. self.assertIs(type(D[int]()), D)
  1845. def test_counter_instantiation(self):
  1846. self.assertIs(type(typing.Counter()), collections.Counter)
  1847. self.assertIs(type(typing.Counter[T]()), collections.Counter)
  1848. self.assertIs(type(typing.Counter[int]()), collections.Counter)
  1849. class C(typing.Counter[T]): pass
  1850. self.assertIs(type(C[int]()), C)
  1851. def test_counter_subclass_instantiation(self):
  1852. class MyCounter(typing.Counter[int]):
  1853. pass
  1854. d = MyCounter()
  1855. self.assertIsInstance(d, MyCounter)
  1856. self.assertIsInstance(d, typing.Counter)
  1857. self.assertIsInstance(d, collections.Counter)
  1858. def test_no_set_instantiation(self):
  1859. with self.assertRaises(TypeError):
  1860. typing.Set()
  1861. with self.assertRaises(TypeError):
  1862. typing.Set[T]()
  1863. with self.assertRaises(TypeError):
  1864. typing.Set[int]()
  1865. def test_set_subclass_instantiation(self):
  1866. class MySet(typing.Set[int]):
  1867. pass
  1868. d = MySet()
  1869. self.assertIsInstance(d, MySet)
  1870. def test_no_frozenset_instantiation(self):
  1871. with self.assertRaises(TypeError):
  1872. typing.FrozenSet()
  1873. with self.assertRaises(TypeError):
  1874. typing.FrozenSet[T]()
  1875. with self.assertRaises(TypeError):
  1876. typing.FrozenSet[int]()
  1877. def test_frozenset_subclass_instantiation(self):
  1878. class MyFrozenSet(typing.FrozenSet[int]):
  1879. pass
  1880. d = MyFrozenSet()
  1881. self.assertIsInstance(d, MyFrozenSet)
  1882. def test_no_tuple_instantiation(self):
  1883. with self.assertRaises(TypeError):
  1884. Tuple()
  1885. with self.assertRaises(TypeError):
  1886. Tuple[T]()
  1887. with self.assertRaises(TypeError):
  1888. Tuple[int]()
  1889. def test_generator(self):
  1890. def foo():
  1891. yield 42
  1892. g = foo()
  1893. self.assertIsSubclass(type(g), typing.Generator)
  1894. def test_no_generator_instantiation(self):
  1895. with self.assertRaises(TypeError):
  1896. typing.Generator()
  1897. with self.assertRaises(TypeError):
  1898. typing.Generator[T, T, T]()
  1899. with self.assertRaises(TypeError):
  1900. typing.Generator[int, int, int]()
  1901. def test_subclassing(self):
  1902. class MMA(typing.MutableMapping):
  1903. pass
  1904. with self.assertRaises(TypeError): # It's abstract
  1905. MMA()
  1906. class MMC(MMA):
  1907. def __getitem__(self, k):
  1908. return None
  1909. def __setitem__(self, k, v):
  1910. pass
  1911. def __delitem__(self, k):
  1912. pass
  1913. def __iter__(self):
  1914. return iter(())
  1915. def __len__(self):
  1916. return 0
  1917. self.assertEqual(len(MMC()), 0)
  1918. assert callable(MMC.update)
  1919. self.assertIsInstance(MMC(), typing.Mapping)
  1920. class MMB(typing.MutableMapping[KT, VT]):
  1921. def __getitem__(self, k):
  1922. return None
  1923. def __setitem__(self, k, v):
  1924. pass
  1925. def __delitem__(self, k):
  1926. pass
  1927. def __iter__(self):
  1928. return iter(())
  1929. def __len__(self):
  1930. return 0
  1931. self.assertEqual(len(MMB()), 0)
  1932. self.assertEqual(len(MMB[str, str]()), 0)
  1933. self.assertEqual(len(MMB[KT, VT]()), 0)
  1934. self.assertNotIsSubclass(dict, MMA)
  1935. self.assertNotIsSubclass(dict, MMB)
  1936. self.assertIsSubclass(MMA, typing.Mapping)
  1937. self.assertIsSubclass(MMB, typing.Mapping)
  1938. self.assertIsSubclass(MMC, typing.Mapping)
  1939. self.assertIsInstance(MMB[KT, VT](), typing.Mapping)
  1940. self.assertIsInstance(MMB[KT, VT](), collections.Mapping)
  1941. self.assertIsSubclass(MMA, collections.Mapping)
  1942. self.assertIsSubclass(MMB, collections.Mapping)
  1943. self.assertIsSubclass(MMC, collections.Mapping)
  1944. self.assertIsSubclass(MMB[str, str], typing.Mapping)
  1945. self.assertIsSubclass(MMC, MMA)
  1946. class It(typing.Iterable): pass
  1947. self.assertNotIsSubclass(list, It)
  1948. class G(typing.Generator[int, int, int]): pass
  1949. def g(): yield 0
  1950. self.assertIsSubclass(G, typing.Generator)
  1951. self.assertIsSubclass(G, typing.Iterable)
  1952. if hasattr(collections, 'Generator'):
  1953. self.assertIsSubclass(G, collections.Generator)
  1954. self.assertIsSubclass(G, collections.Iterable)
  1955. self.assertNotIsSubclass(type(g), G)
  1956. def test_subclassing_subclasshook(self):
  1957. class Base(typing.Iterable):
  1958. @classmethod
  1959. def __subclasshook__(cls, other):
  1960. if other.__name__ == 'Foo':
  1961. return True
  1962. else:
  1963. return False
  1964. class C(Base): pass
  1965. class Foo: pass
  1966. class Bar: pass
  1967. self.assertIsSubclass(Foo, Base)
  1968. self.assertIsSubclass(Foo, C)
  1969. self.assertNotIsSubclass(Bar, C)
  1970. def test_subclassing_register(self):
  1971. class A(typing.Container): pass
  1972. class B(A): pass
  1973. class C: pass
  1974. A.register(C)
  1975. self.assertIsSubclass(C, A)
  1976. self.assertNotIsSubclass(C, B)
  1977. class D: pass
  1978. B.register(D)
  1979. self.assertIsSubclass(D, A)
  1980. self.assertIsSubclass(D, B)
  1981. class M(): pass
  1982. collections.MutableMapping.register(M)
  1983. self.assertIsSubclass(M, typing.Mapping)
  1984. def test_collections_as_base(self):
  1985. class M(collections.Mapping): pass
  1986. self.assertIsSubclass(M, typing.Mapping)
  1987. self.assertIsSubclass(M, typing.Iterable)
  1988. class S(collections.MutableSequence): pass
  1989. self.assertIsSubclass(S, typing.MutableSequence)
  1990. self.assertIsSubclass(S, typing.Iterable)
  1991. class It(collections.Iterable): pass
  1992. self.assertIsSubclass(It, typing.Iterable)
  1993. class A(collections.Mapping): pass
  1994. class B: pass
  1995. A.register(B)
  1996. self.assertIsSubclass(B, typing.Mapping)
  1997. class OtherABCTests(BaseTestCase):
  1998. def test_contextmanager(self):
  1999. @contextlib.contextmanager
  2000. def manager():
  2001. yield 42
  2002. cm = manager()
  2003. self.assertIsInstance(cm, typing.ContextManager)
  2004. self.assertNotIsInstance(42, typing.ContextManager)
  2005. class TypeTests(BaseTestCase):
  2006. def test_type_basic(self):
  2007. class User(object): pass
  2008. class BasicUser(User): pass
  2009. class ProUser(User): pass
  2010. def new_user(user_class):
  2011. # type: (Type[User]) -> User
  2012. return user_class()
  2013. new_user(BasicUser)
  2014. def test_type_typevar(self):
  2015. class User(object): pass
  2016. class BasicUser(User): pass
  2017. class ProUser(User): pass
  2018. global U
  2019. U = TypeVar('U', bound=User)
  2020. def new_user(user_class):
  2021. # type: (Type[U]) -> U
  2022. return user_class()
  2023. new_user(BasicUser)
  2024. def test_type_optional(self):
  2025. A = Optional[Type[BaseException]] # noqa
  2026. def foo(a):
  2027. # type: (A) -> Optional[BaseException]
  2028. if a is None:
  2029. return None
  2030. else:
  2031. return a()
  2032. assert isinstance(foo(KeyboardInterrupt), KeyboardInterrupt)
  2033. assert foo(None) is None
  2034. class NewTypeTests(BaseTestCase):
  2035. def test_basic(self):
  2036. UserId = NewType('UserId', int)
  2037. UserName = NewType('UserName', str)
  2038. self.assertIsInstance(UserId(5), int)
  2039. self.assertIsInstance(UserName('Joe'), type('Joe'))
  2040. self.assertEqual(UserId(5) + 1, 6)
  2041. def test_errors(self):
  2042. UserId = NewType('UserId', int)
  2043. UserName = NewType('UserName', str)
  2044. with self.assertRaises(TypeError):
  2045. issubclass(UserId, int)
  2046. with self.assertRaises(TypeError):
  2047. class D(UserName):
  2048. pass
  2049. class NamedTupleTests(BaseTestCase):
  2050. def test_basics(self):
  2051. Emp = NamedTuple('Emp', [('name', str), ('id', int)])
  2052. self.assertIsSubclass(Emp, tuple)
  2053. joe = Emp('Joe', 42)
  2054. jim = Emp(name='Jim', id=1)
  2055. self.assertIsInstance(joe, Emp)
  2056. self.assertIsInstance(joe, tuple)
  2057. self.assertEqual(joe.name, 'Joe')
  2058. self.assertEqual(joe.id, 42)
  2059. self.assertEqual(jim.name, 'Jim')
  2060. self.assertEqual(jim.id, 1)
  2061. self.assertEqual(Emp.__name__, 'Emp')
  2062. self.assertEqual(Emp._fields, ('name', 'id'))
  2063. self.assertEqual(Emp._field_types, dict(name=str, id=int))
  2064. def test_pickle(self):
  2065. global Emp # pickle wants to reference the class by name
  2066. Emp = NamedTuple('Emp', [('name', str), ('id', int)])
  2067. jane = Emp('jane', 37)
  2068. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2069. z = pickle.dumps(jane, proto)
  2070. jane2 = pickle.loads(z)
  2071. self.assertEqual(jane2, jane)
  2072. class TypedDictTests(BaseTestCase):
  2073. def test_basics_iterable_syntax(self):
  2074. Emp = TypedDict(b'Emp', {'name': str, 'id': int})
  2075. self.assertIsSubclass(Emp, dict)
  2076. self.assertIsSubclass(Emp, typing.MutableMapping)
  2077. if sys.version_info[0] >= 3:
  2078. import collections.abc
  2079. self.assertNotIsSubclass(Emp, collections.abc.Sequence)
  2080. jim = Emp(name='Jim', id=1)
  2081. self.assertIs(type(jim), dict)
  2082. self.assertEqual(jim['name'], 'Jim')
  2083. self.assertEqual(jim['id'], 1)
  2084. self.assertEqual(Emp.__name__, 'Emp')
  2085. self.assertEqual(Emp.__module__, __name__)
  2086. self.assertEqual(Emp.__bases__, (dict,))
  2087. self.assertEqual(Emp.__annotations__, {'name': str, 'id': int})
  2088. self.assertEqual(Emp.__total__, True)
  2089. def test_basics_keywords_syntax(self):
  2090. Emp = TypedDict(b'Emp', name=str, id=int)
  2091. self.assertIsSubclass(Emp, dict)
  2092. self.assertIsSubclass(Emp, typing.MutableMapping)
  2093. if sys.version_info[0] >= 3:
  2094. import collections.abc
  2095. self.assertNotIsSubclass(Emp, collections.abc.Sequence)
  2096. jim = Emp(name='Jim', id=1)
  2097. self.assertIs(type(jim), dict)
  2098. self.assertEqual(jim['name'], 'Jim')
  2099. self.assertEqual(jim['id'], 1)
  2100. self.assertEqual(Emp.__name__, 'Emp')
  2101. self.assertEqual(Emp.__module__, __name__)
  2102. self.assertEqual(Emp.__bases__, (dict,))
  2103. self.assertEqual(Emp.__annotations__, {'name': str, 'id': int})
  2104. self.assertEqual(Emp.__total__, True)
  2105. def test_typeddict_errors(self):
  2106. Emp = TypedDict(b'Emp', {'name': str, 'id': int})
  2107. self.assertEqual(TypedDict.__module__, 'typing')
  2108. jim = Emp(name='Jim', id=1)
  2109. with self.assertRaises(TypeError):
  2110. isinstance({}, Emp)
  2111. with self.assertRaises(TypeError):
  2112. isinstance(jim, Emp)
  2113. with self.assertRaises(TypeError):
  2114. issubclass(dict, Emp)
  2115. with self.assertRaises(TypeError):
  2116. TypedDict('Hi', x=1)
  2117. with self.assertRaises(TypeError):
  2118. TypedDict('Hi', [('x', int), ('y', 1)])
  2119. with self.assertRaises(TypeError):
  2120. TypedDict('Hi', [('x', int)], y=int)
  2121. def test_pickle(self):
  2122. global EmpD # pickle wants to reference the class by name
  2123. EmpD = TypedDict(b'EmpD', name=str, id=int)
  2124. jane = EmpD({'name': 'jane', 'id': 37})
  2125. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2126. z = pickle.dumps(jane, proto)
  2127. jane2 = pickle.loads(z)
  2128. self.assertEqual(jane2, jane)
  2129. self.assertEqual(jane2, {'name': 'jane', 'id': 37})
  2130. ZZ = pickle.dumps(EmpD, proto)
  2131. EmpDnew = pickle.loads(ZZ)
  2132. self.assertEqual(EmpDnew({'name': 'jane', 'id': 37}), jane)
  2133. def test_optional(self):
  2134. EmpD = TypedDict(b'EmpD', name=str, id=int)
  2135. self.assertEqual(typing.Optional[EmpD], typing.Union[None, EmpD])
  2136. self.assertNotEqual(typing.List[EmpD], typing.Tuple[EmpD])
  2137. def test_total(self):
  2138. D = TypedDict(b'D', {'x': int}, total=False)
  2139. self.assertEqual(D(), {})
  2140. self.assertEqual(D(x=1), {'x': 1})
  2141. self.assertEqual(D.__total__, False)
  2142. class IOTests(BaseTestCase):
  2143. def test_io_submodule(self):
  2144. from typing.io import IO, TextIO, BinaryIO, __all__, __name__
  2145. self.assertIs(IO, typing.IO)
  2146. self.assertIs(TextIO, typing.TextIO)
  2147. self.assertIs(BinaryIO, typing.BinaryIO)
  2148. self.assertEqual(set(__all__), set(['IO', 'TextIO', 'BinaryIO']))
  2149. self.assertEqual(__name__, 'typing.io')
  2150. class RETests(BaseTestCase):
  2151. # Much of this is really testing _TypeAlias.
  2152. def test_basics(self):
  2153. pat = re.compile('[a-z]+', re.I)
  2154. self.assertIsSubclass(pat.__class__, Pattern)
  2155. self.assertIsSubclass(type(pat), Pattern)
  2156. self.assertIsInstance(pat, Pattern)
  2157. mat = pat.search('12345abcde.....')
  2158. self.assertIsSubclass(mat.__class__, Match)
  2159. self.assertIsSubclass(type(mat), Match)
  2160. self.assertIsInstance(mat, Match)
  2161. # these should just work
  2162. Pattern[Union[str, bytes]]
  2163. Match[Union[bytes, str]]
  2164. def test_alias_equality(self):
  2165. self.assertEqual(Pattern[str], Pattern[str])
  2166. self.assertNotEqual(Pattern[str], Pattern[bytes])
  2167. self.assertNotEqual(Pattern[str], Match[str])
  2168. self.assertNotEqual(Pattern[str], str)
  2169. def test_errors(self):
  2170. with self.assertRaises(TypeError):
  2171. # Doesn't fit AnyStr.
  2172. Pattern[int]
  2173. with self.assertRaises(TypeError):
  2174. # Can't change type vars?
  2175. Match[T]
  2176. m = Match[Union[str, bytes]]
  2177. with self.assertRaises(TypeError):
  2178. # Too complicated?
  2179. m[str]
  2180. with self.assertRaises(TypeError):
  2181. # We don't support isinstance().
  2182. isinstance(42, Pattern[str])
  2183. with self.assertRaises(TypeError):
  2184. # We don't support issubclass().
  2185. issubclass(Pattern[bytes], Pattern[str])
  2186. def test_repr(self):
  2187. self.assertEqual(repr(Pattern), 'Pattern[~AnyStr]')
  2188. self.assertEqual(repr(Pattern[unicode]), 'Pattern[unicode]')
  2189. self.assertEqual(repr(Pattern[str]), 'Pattern[str]')
  2190. self.assertEqual(repr(Match), 'Match[~AnyStr]')
  2191. self.assertEqual(repr(Match[unicode]), 'Match[unicode]')
  2192. self.assertEqual(repr(Match[str]), 'Match[str]')
  2193. def test_re_submodule(self):
  2194. from typing.re import Match, Pattern, __all__, __name__
  2195. self.assertIs(Match, typing.Match)
  2196. self.assertIs(Pattern, typing.Pattern)
  2197. self.assertEqual(set(__all__), set(['Match', 'Pattern']))
  2198. self.assertEqual(__name__, 'typing.re')
  2199. def test_cannot_subclass(self):
  2200. with self.assertRaises(TypeError) as ex:
  2201. class A(typing.Match):
  2202. pass
  2203. self.assertEqual(str(ex.exception),
  2204. "Cannot subclass typing._TypeAlias")
  2205. class AllTests(BaseTestCase):
  2206. """Tests for __all__."""
  2207. def test_all(self):
  2208. from typing import __all__ as a
  2209. # Just spot-check the first and last of every category.
  2210. self.assertIn('AbstractSet', a)
  2211. self.assertIn('ValuesView', a)
  2212. self.assertIn('cast', a)
  2213. self.assertIn('overload', a)
  2214. # Check that io and re are not exported.
  2215. self.assertNotIn('io', a)
  2216. self.assertNotIn('re', a)
  2217. # Spot-check that stdlib modules aren't exported.
  2218. self.assertNotIn('os', a)
  2219. self.assertNotIn('sys', a)
  2220. # Check that Text is defined.
  2221. self.assertIn('Text', a)
  2222. # Check previously missing class.
  2223. self.assertIn('SupportsComplex', a)
  2224. def test_respect_no_type_check(self):
  2225. @typing.no_type_check
  2226. class NoTpCheck(object):
  2227. class Inn(object):
  2228. def __init__(self, x):
  2229. # type: (this is not actually a type) -> None # noqa
  2230. pass
  2231. self.assertTrue(NoTpCheck.__no_type_check__)
  2232. self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__)
  2233. def test_get_type_hints_dummy(self):
  2234. def foo(x):
  2235. # type: (int) -> int
  2236. return x + 1
  2237. self.assertIsNone(typing.get_type_hints(foo))
  2238. # def test_typing_compiles_with_opt(self):
  2239. # file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
  2240. # 'typing.py')
  2241. # try:
  2242. # subprocess.check_output([sys.executable, '-OO', file_path],
  2243. # stderr=subprocess.STDOUT)
  2244. # except subprocess.CalledProcessError:
  2245. # self.fail('Module does not compile with optimize=2 (-OO flag).')
  2246. if __name__ == '__main__':
  2247. main()