run-classes.test 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505
  1. [case testEmptyClass]
  2. class Empty: pass
  3. def f(e: Empty) -> Empty:
  4. return e
  5. [file driver.py]
  6. from native import Empty, f
  7. print(isinstance(Empty, type))
  8. print(Empty)
  9. print(str(Empty())[:20])
  10. e = Empty()
  11. print(f(e) is e)
  12. [out]
  13. True
  14. <class 'native.Empty'>
  15. <native.Empty object
  16. True
  17. [case testClassWithFields]
  18. class C:
  19. x: int
  20. y: int
  21. z: 'D'
  22. class D:
  23. pass
  24. [file driver.py]
  25. from native import C
  26. from testutil import assertRaises
  27. c = C()
  28. assert not hasattr(c, 'x')
  29. assert not hasattr(c, 'y')
  30. c.x = 1
  31. c.y = 2
  32. print(c.x)
  33. print(c.y)
  34. c.x = 10**30
  35. print(c.x)
  36. c.x = 10**30+1
  37. print(c.x)
  38. assert hasattr(c, 'x')
  39. assert hasattr(c, 'y')
  40. assert not hasattr(c, 'z')
  41. with assertRaises(AttributeError, "'C' object attribute 'x' cannot be deleted"):
  42. del c.x
  43. assert hasattr(c, 'x')
  44. assert hasattr(c, 'y')
  45. with assertRaises(AttributeError, "'C' object attribute 'y' cannot be deleted"):
  46. del c.y
  47. assert hasattr(c, 'y')
  48. c.x = 10**30+2
  49. print(c.x)
  50. assert hasattr(c, 'x')
  51. [out]
  52. 1
  53. 2
  54. 1000000000000000000000000000000
  55. 1000000000000000000000000000001
  56. 1000000000000000000000000000002
  57. [case testClassWithDeletableAttributes]
  58. from typing import Any, cast
  59. from testutil import assertRaises
  60. class C:
  61. __deletable__ = ['x', 'y']
  62. x: int
  63. y: int
  64. z: int
  65. def test_delete() -> None:
  66. c = C()
  67. c.x = 1
  68. c.y = 2
  69. c.z = 3
  70. del c.x
  71. del c.y
  72. assert c.z == 3
  73. with assertRaises(AttributeError, "attribute 'x' of 'C' undefined"):
  74. c.x
  75. with assertRaises(AttributeError, "attribute 'y' of 'C' undefined"):
  76. c.y
  77. def test_delete_any() -> None:
  78. c: Any = C()
  79. c.x = 1
  80. c.y = 2
  81. c.z = 3
  82. del c.x
  83. del c.y
  84. with assertRaises(AttributeError, "'C' object attribute 'z' cannot be deleted"):
  85. del c.z
  86. assert c.z == 3
  87. with assertRaises(AttributeError):
  88. c.x
  89. with assertRaises(AttributeError):
  90. c.y
  91. class Base:
  92. __deletable__ = ['a']
  93. a: int
  94. b: int
  95. class Deriv(Base):
  96. __deletable__ = ('c',)
  97. c: str
  98. d: str
  99. def test_delete_with_inheritance() -> None:
  100. d = Deriv()
  101. d.a = 0
  102. d.b = 1
  103. d.c = 'X'
  104. d.d = 'Y'
  105. del d.a
  106. with assertRaises(AttributeError):
  107. d.a
  108. del d.c
  109. with assertRaises(AttributeError):
  110. d.c
  111. assert d.b == 1
  112. assert d.d == 'Y'
  113. def test_delete_with_inheritance_any() -> None:
  114. d: Any = Deriv()
  115. d.a = 0
  116. d.b = 1
  117. d.c = 'X'
  118. d.d = 'Y'
  119. del d.a
  120. with assertRaises(AttributeError):
  121. d.a
  122. del d.c
  123. with assertRaises(AttributeError):
  124. d.c
  125. with assertRaises(AttributeError):
  126. del d.b
  127. assert d.b == 1
  128. with assertRaises(AttributeError):
  129. del d.d
  130. assert d.d == 'Y'
  131. def decorator(cls):
  132. return cls
  133. @decorator
  134. class NonExt:
  135. x: int
  136. y: int
  137. # No effect in a non-native class
  138. __deletable__ = ['x']
  139. def test_non_ext() -> None:
  140. n = NonExt()
  141. n.x = 2
  142. n.y = 3
  143. del n.x
  144. del n.y
  145. with assertRaises(AttributeError):
  146. n.x
  147. with assertRaises(AttributeError):
  148. n.y
  149. def test_non_ext_any() -> None:
  150. n: Any = NonExt()
  151. n.x = 2
  152. n.y = 3
  153. del n.x
  154. del n.y
  155. with assertRaises(AttributeError):
  156. n.x
  157. with assertRaises(AttributeError):
  158. n.y
  159. [case testNonExtMisc]
  160. from typing import Any, overload
  161. def decorator(cls) -> Any:
  162. return cls
  163. @decorator
  164. class C:
  165. def __init__(self) -> None:
  166. self.c = 3
  167. def get_c(self) -> int:
  168. return self.c
  169. @decorator
  170. class B(C):
  171. def __init__(self) -> None:
  172. super().__init__()
  173. self.b = 2
  174. def get_b(self) -> int:
  175. return self.b
  176. @decorator
  177. class A(B):
  178. def __init__(self) -> None:
  179. super().__init__()
  180. self.a = 1
  181. @classmethod
  182. def constant(cls) -> int:
  183. return 4
  184. def get_a(self) -> int:
  185. return self.a
  186. @decorator
  187. class Overload:
  188. @overload
  189. def get(self, index: int) -> int: ...
  190. @overload
  191. def get(self, index: str) -> str: ...
  192. def get(self, index: Any) -> Any:
  193. return index
  194. def get(c: Overload, s: str) -> str:
  195. return c.get(s)
  196. @decorator
  197. class Var:
  198. x = 'xy'
  199. def get_class_var() -> str:
  200. return Var.x
  201. [file driver.py]
  202. from native import A, Overload, get, get_class_var
  203. a = A()
  204. assert a.a == 1
  205. assert a.b == 2
  206. assert a.c == 3
  207. assert a.get_a() == 1
  208. assert a.get_b() == 2
  209. assert a.get_c() == 3
  210. assert A.constant() == 4
  211. o = Overload()
  212. assert get(o, "test") == "test"
  213. assert o.get(20) == 20
  214. assert get_class_var() == 'xy'
  215. [case testEnum]
  216. from enum import Enum
  217. class TestEnum(Enum):
  218. _order_ = "a b"
  219. a : int = 1
  220. b : int = 2
  221. @classmethod
  222. def test(cls) -> int:
  223. return 3
  224. assert TestEnum.test() == 3
  225. import enum
  226. class Pokemon(enum.Enum):
  227. magikarp = 1
  228. squirtle = 2
  229. slowbro = 3
  230. assert Pokemon.magikarp.value == 1
  231. assert Pokemon.squirtle.name == 'squirtle'
  232. [file other.py]
  233. # Force a multi-module test to make sure we can compile multi-file with
  234. # non-extension classes
  235. [file driver.py]
  236. import sys
  237. # "_order_" isn't supported in 3.5
  238. if sys.version_info[:2] > (3, 5):
  239. from native import TestEnum
  240. assert TestEnum.a.name == 'a'
  241. assert TestEnum.a.value == 1
  242. assert TestEnum.b.name == 'b'
  243. assert TestEnum.b.value == 2
  244. [case testGetAttribute]
  245. class C:
  246. x: int
  247. y: int
  248. def getx(c: C) -> int:
  249. return c.x
  250. def gety(c: C) -> int:
  251. return c.y
  252. [file driver.py]
  253. from native import C, getx, gety
  254. c = C()
  255. c.x = 10**30
  256. c.y = 10**30 + 1
  257. print(getx(c))
  258. print(gety(c))
  259. [out]
  260. 1000000000000000000000000000000
  261. 1000000000000000000000000000001
  262. [case testSetAttribute]
  263. class C:
  264. x: int
  265. y: int
  266. def setx(c: C, v: int) -> None:
  267. c.x = v
  268. def sety(c: C, v: int) -> None:
  269. c.y = v
  270. [file driver.py]
  271. from native import C, setx, sety
  272. c = C()
  273. setx(c, 10**30)
  274. sety(c, 10**30 + 1)
  275. print(c.x)
  276. print(c.y)
  277. setx(c, 4)
  278. sety(c, 5)
  279. print(c.x, c.y)
  280. setx(c, 10**30 + 2)
  281. sety(c, 10**30 + 3)
  282. print(c.x)
  283. print(c.y)
  284. [out]
  285. 1000000000000000000000000000000
  286. 1000000000000000000000000000001
  287. 4 5
  288. 1000000000000000000000000000002
  289. 1000000000000000000000000000003
  290. [case testAttributeTypes]
  291. from typing import List, Tuple
  292. class C:
  293. a: List[int]
  294. b: bool
  295. c: C
  296. d: object
  297. e: int
  298. def setattrs(o: C, a: List[int], b: bool, c: C) -> None:
  299. o.a = a
  300. o.b = b
  301. o.c = c
  302. def getattrs(o: C) -> Tuple[List[int], bool, C]:
  303. return o.a, o.b, o.c
  304. [file driver.py]
  305. from native import C, setattrs, getattrs
  306. from testutil import assertRaises
  307. c1 = C()
  308. c2 = C()
  309. aa = [2]
  310. setattrs(c1, aa, True, c2)
  311. a, b, c = getattrs(c1)
  312. assert a is aa
  313. assert b is True
  314. assert c is c2
  315. o = object()
  316. c1.d = o
  317. assert c1.d is o
  318. c3 = C()
  319. with assertRaises(AttributeError, "attribute 'a' of 'C' undefined"):
  320. c3.a
  321. with assertRaises(AttributeError, "attribute 'b' of 'C' undefined"):
  322. c3.b
  323. with assertRaises(AttributeError, "attribute 'c' of 'C' undefined"):
  324. c3.c
  325. with assertRaises(AttributeError, "attribute 'd' of 'C' undefined"):
  326. c3.d
  327. with assertRaises(AttributeError, "attribute 'e' of 'C' undefined"):
  328. c3.e
  329. [case testInitMethodWithMissingNoneReturnAnnotation]
  330. class C:
  331. def __init__(self):
  332. self.x = 42
  333. [file driver.py]
  334. from native import C
  335. c = C()
  336. assert c is not None
  337. assert c.x == 42
  338. [case testConstructClassWithDefaultConstructor]
  339. class C:
  340. a: int
  341. b: int
  342. def f() -> C:
  343. c = C()
  344. c.a = 13
  345. return c
  346. [file driver.py]
  347. from native import f, C
  348. c = f()
  349. assert c.a == 13
  350. assert type(c) == C
  351. assert not hasattr(c, 'b')
  352. [case testCastUserClass]
  353. from typing import List
  354. class C:
  355. x: int
  356. def f(a: List[C]) -> C:
  357. return a[0]
  358. [file driver.py]
  359. from native import f, C
  360. c = C()
  361. assert f([c]) is c
  362. [case testClass1]
  363. class A:
  364. def __init__(self, x: int) -> None:
  365. self.x = x
  366. def foo(self) -> int:
  367. return self.x+1
  368. def foo() -> int:
  369. a = A(20)
  370. return a.foo()
  371. [file driver.py]
  372. from native import A, foo
  373. a = A(10)
  374. assert a.foo() == 11
  375. assert foo() == 21
  376. [case testGenericClass]
  377. from typing import TypeVar, Generic, Sequence
  378. T = TypeVar('T')
  379. class C(Generic[T]):
  380. x: T
  381. def __init__(self, x: T) -> None:
  382. self.x = x
  383. def get(self) -> T:
  384. return self.x
  385. def set(self, y: T) -> None:
  386. self.x = y
  387. # Test subclassing generic classes both with and without a generic param
  388. class A(Sequence[int]):
  389. pass
  390. class B(Sequence[T]):
  391. pass
  392. def f(c: C[int]) -> int:
  393. y = c.get()
  394. d = C[int](2)
  395. c.set(c.get() + 1 + d.get())
  396. c.x = c.x + 2
  397. return c.x
  398. [file driver.py]
  399. from native import C, f
  400. c = C(6)
  401. assert f(c) == 11
  402. c.x = 'x'
  403. assert c.x == 'x'
  404. c.set([1])
  405. assert c.x == [1]
  406. assert c.get() == [1]
  407. [case testSubclass1]
  408. from typing import Tuple
  409. class A:
  410. def __init__(self) -> None:
  411. self.x = 10
  412. def hi(self, suffix: str) -> str:
  413. return str(self.x) + suffix
  414. class B(A):
  415. def __init__(self) -> None:
  416. self.x = 20
  417. self.y = 'world'
  418. def hi(self, suffix: str) -> str:
  419. return 'hello ' + str(self.y) + suffix
  420. def use_a(x: A) -> Tuple[int, str]:
  421. return (x.x, x.hi(''))
  422. def use_b(x: B) -> str:
  423. return x.hi('')
  424. [file driver.py]
  425. from native import A, B, use_a, use_b
  426. a = A()
  427. b = B()
  428. assert use_a(a) == (10, '10')
  429. assert use_a(b) == (20, 'hello world')
  430. assert a.x == 10
  431. assert b.x == 20
  432. assert b.y == 'world'
  433. assert a.hi('!') == '10!'
  434. assert b.hi('!') == 'hello world!'
  435. assert use_b(b) == 'hello world'
  436. [case testSubclassSpecialize1]
  437. class A:
  438. def foo(self, x: int) -> object:
  439. print('A')
  440. return str(x)
  441. def bar(self, x: int) -> None:
  442. print(x + 1)
  443. class B(A):
  444. def foo(self, x: object) -> int:
  445. print('B')
  446. return id(x)
  447. def bar(self, x: object) -> None:
  448. print(x)
  449. def use_a(x: A, y: int) -> object:
  450. x.bar(10)
  451. return x.foo(y)
  452. def use_b(x: B, y: object) -> int:
  453. return x.foo(y)
  454. [file driver.py]
  455. from native import A, B, use_a, use_b
  456. a = A()
  457. b = B()
  458. o = object()
  459. i = 10
  460. assert a.foo(10) == '10'
  461. assert b.foo(o) == id(o)
  462. assert use_a(a, 10) == '10'
  463. assert use_b(b, o) == id(o)
  464. assert use_a(b, i) == id(i)
  465. [out]
  466. A
  467. B
  468. 11
  469. A
  470. B
  471. 10
  472. B
  473. [case testSubclassSpecialize2]
  474. class A:
  475. def foo(self, x: int) -> object:
  476. print('A')
  477. return str(x)
  478. class B(A):
  479. def foo(self, x: object) -> object:
  480. print('B')
  481. return x
  482. class C(B):
  483. def foo(self, x: object) -> int:
  484. print('C')
  485. return id(x)
  486. def use_a(x: A, y: int) -> object:
  487. return x.foo(y)
  488. def use_b(x: B, y: object) -> object:
  489. return x.foo(y)
  490. def use_c(x: C, y: object) -> int:
  491. return x.foo(y)
  492. [file driver.py]
  493. from native import A, B, C, use_a, use_b, use_c
  494. a = A()
  495. b = B()
  496. c = C()
  497. o = object()
  498. i = 10
  499. assert a.foo(10) == '10'
  500. assert b.foo(o) == o
  501. assert c.foo(o) == id(o)
  502. assert use_a(a, 10) == '10'
  503. assert use_a(b, i) is i
  504. assert use_a(c, i) == id(i)
  505. assert use_b(b, o) == o
  506. assert use_b(c, o) == id(o)
  507. assert use_c(c, o) == id(o)
  508. [out]
  509. A
  510. B
  511. C
  512. A
  513. B
  514. C
  515. B
  516. C
  517. C
  518. [case testIsInstance]
  519. from typing import Optional
  520. class X: pass
  521. class A(X): pass
  522. class B(A): pass
  523. def isa(x: object) -> bool:
  524. return isinstance(x, A)
  525. def isint(x: object) -> bool:
  526. return isinstance(x, int)
  527. def isstr(x: object) -> bool:
  528. return isinstance(x, str)
  529. def islist(x: object) -> bool:
  530. return isinstance(x, list)
  531. def ist(x: object, t: object) -> bool: # TODO: Second argument should be 'type'
  532. return isinstance(x, t)
  533. def pointless(x: Optional[X]) -> str:
  534. if isinstance(x, A):
  535. return str(x)
  536. return ''
  537. [file driver.py]
  538. from native import X, A, B, isa, isint, isstr, islist, ist
  539. assert isa(1) == False
  540. assert isa(A()) == True
  541. assert isa(B()) == True
  542. assert isa(X()) == False
  543. assert isint(1) == True
  544. assert isint('') == False
  545. assert isint(A()) == False
  546. assert isstr(1) == False
  547. assert isstr('') == True
  548. assert islist(1) == False
  549. assert islist([]) == True
  550. assert ist(1, int) == True
  551. assert ist(1, str) == False
  552. try:
  553. ist(1, 2)
  554. except TypeError:
  555. pass
  556. else:
  557. assert False
  558. [case testSubclassUninitAttr]
  559. class X:
  560. x: int
  561. class A(X):
  562. pass
  563. [file driver.py]
  564. import traceback
  565. from native import A
  566. try:
  567. A().x
  568. except AttributeError:
  569. traceback.print_exc()
  570. [out]
  571. Traceback (most recent call last):
  572. File "driver.py", line 4, in <module>
  573. A().x
  574. AttributeError: attribute 'x' of 'X' undefined
  575. [case testClassMethods]
  576. from typing import ClassVar, Any
  577. from typing_extensions import final
  578. from mypy_extensions import mypyc_attr
  579. from interp import make_interpreted_subclass
  580. class C:
  581. lurr: ClassVar[int] = 9
  582. @staticmethod
  583. def foo(x: int) -> int:
  584. return 10 + x
  585. @classmethod
  586. def bar(cls, x: int) -> int:
  587. return cls.lurr + x
  588. @staticmethod
  589. def baz(x: int, y: int = 10) -> int:
  590. return y - x
  591. @classmethod
  592. def quux(cls, x: int, y: int = 10) -> int:
  593. return y - x
  594. @classmethod
  595. def call_other(cls, x: int) -> int:
  596. return cls.quux(x, 3)
  597. class D(C):
  598. def f(self) -> int:
  599. return super().foo(1) + super().bar(2) + super().baz(10) + super().quux(10)
  600. def ctest1() -> int:
  601. return C.foo(1) + C.bar(2) + C.baz(10) + C.quux(10) + C.quux(y=10, x=9)
  602. def ctest2() -> int:
  603. c = C()
  604. return c.foo(1) + c.bar(2) + c.baz(10)
  605. CAny: Any = C
  606. def test_classmethod_using_any() -> None:
  607. assert CAny.foo(10) == 20
  608. assert CAny.bar(10) == 19
  609. def test_classmethod_on_instance() -> None:
  610. c = C()
  611. assert c.foo(10) == 20
  612. assert c.bar(10) == 19
  613. assert c.call_other(1) == 2
  614. def test_classmethod_misc() -> None:
  615. assert ctest1() == 23
  616. assert ctest2() == 22
  617. assert C.call_other(2) == 1
  618. def test_classmethod_using_super() -> None:
  619. d = D()
  620. assert d.f() == 22
  621. @final
  622. class F1:
  623. @classmethod
  624. def f(cls, x: int) -> int:
  625. return cls.g(x)
  626. @classmethod
  627. def g(cls, x: int) -> int:
  628. return x + 1
  629. class F2: # Implicitly final (no subclasses)
  630. @classmethod
  631. def f(cls, x: int) -> int:
  632. return cls.g(x)
  633. @classmethod
  634. def g(cls, x: int) -> int:
  635. return x + 1
  636. def test_classmethod_of_final_class() -> None:
  637. assert F1.f(5) == 6
  638. assert F2.f(7) == 8
  639. @mypyc_attr(allow_interpreted_subclasses=True)
  640. class CI:
  641. @classmethod
  642. def f(cls, x: int) -> int:
  643. return cls.g(x)
  644. @classmethod
  645. def g(cls, x: int) -> int:
  646. return x + 1
  647. def test_classmethod_with_allow_interpreted() -> None:
  648. assert CI.f(4) == 5
  649. sub = make_interpreted_subclass(CI)
  650. assert sub.f(4) == 7
  651. [file interp.py]
  652. def make_interpreted_subclass(base):
  653. class Sub(base):
  654. @classmethod
  655. def g(cls, x: int) -> int:
  656. return x + 3
  657. return Sub
  658. [case testSuper]
  659. from mypy_extensions import trait
  660. from typing import List
  661. class A:
  662. def __init__(self, x: int) -> None:
  663. self.x = x
  664. def foo(self, x: int) -> int:
  665. return x
  666. class B(A):
  667. def __init__(self, x: int, y: int) -> None:
  668. super().__init__(x)
  669. self.y = y
  670. def foo(self, x: int) -> int:
  671. return super().foo(x+1)
  672. class C(B):
  673. def __init__(self, x: int, y: int) -> None:
  674. super(C, self).__init__(x, y + 1)
  675. def foo(self, x: int) -> int:
  676. # should go to A, not B
  677. return super(B, self).foo(x+1)
  678. class X:
  679. def __init__(self, x: int) -> None:
  680. self.x = x
  681. class Y(X):
  682. pass
  683. class Z(Y):
  684. def __init__(self, x: int, y: int) -> None:
  685. super().__init__(x)
  686. self.y = y
  687. @trait
  688. class T:
  689. def v_int(self, x: int) -> None: pass
  690. def v_list(self, x: List[int]) -> None:
  691. if x:
  692. self.v_int(x[0])
  693. self.v_list(x[1:])
  694. class PrintList(T):
  695. def v_int(self, x: int) -> None:
  696. print(x)
  697. def v_list(self, x: List[int]) -> None:
  698. print('yo!')
  699. super().v_list(x)
  700. [file driver.py]
  701. import traceback
  702. from native import *
  703. b = B(10, 20)
  704. assert b.x == 10 and b.y == 20
  705. c = C(10, 20)
  706. assert c.x == 10 and c.y == 21
  707. z = Z(10, 20)
  708. assert z.x == 10 and z.y == 20
  709. assert c.foo(10) == 11
  710. PrintList().v_list([1,2,3])
  711. [out]
  712. yo!
  713. 1
  714. yo!
  715. 2
  716. yo!
  717. 3
  718. yo!
  719. [case testSubclassException]
  720. class Failure(Exception):
  721. def __init__(self, x: int) -> None:
  722. self.x = x
  723. def foo() -> None:
  724. raise Failure(10)
  725. def heyo() -> int:
  726. try:
  727. foo()
  728. except Failure as e:
  729. return e.x
  730. return -1
  731. [file driver.py]
  732. from native import foo, heyo, Failure
  733. try:
  734. foo()
  735. except Failure as e:
  736. assert str(e) == '10'
  737. assert e.x == 10
  738. heyo()
  739. [case testSubclassDict]
  740. from typing import Dict
  741. class WelpDict(Dict[str, int]):
  742. def __init__(self) -> None:
  743. self.emarhavil = 3
  744. def foo(self) -> int:
  745. return self.emarhavil
  746. def welp() -> int:
  747. x = WelpDict()
  748. x['a'] = 10
  749. x['b'] = 15
  750. x.emarhavil = 5
  751. return x['a'] + x['b'] + x.emarhavil + x.foo()
  752. [file driver.py]
  753. from native import welp
  754. assert welp() == 35
  755. [case testSubclassPy]
  756. from b import B, V
  757. class A(B):
  758. def __init__(self, x: int, y: int) -> None:
  759. super().__init__(y)
  760. self.x = x
  761. def foo(self, x: int) -> int:
  762. print("hi", x)
  763. return x+1
  764. class C(V[int]):
  765. def f(self) -> int: return 10
  766. assert isinstance(C(), V)
  767. def f(x: A) -> None:
  768. print(x.x)
  769. print(x.y)
  770. print(x.foo(20))
  771. [file b.py]
  772. from typing import Generic, TypeVar
  773. T = TypeVar('T')
  774. class B:
  775. def __init__(self, y: int) -> None:
  776. self.y = y
  777. def foo(self, x: int) -> int:
  778. print("parent!")
  779. return x + self.y
  780. def bar(self) -> None:
  781. print("hello!", self.y)
  782. class V(Generic[T]):
  783. def f(self) -> T:
  784. raise Exception('unimplemented')
  785. [file driver.py]
  786. import native
  787. a = native.A(10, 20)
  788. a.foo(10)
  789. a.bar()
  790. native.f(a)
  791. [out]
  792. hi 10
  793. hello! 20
  794. 10
  795. 20
  796. hi 20
  797. 21
  798. [case testDisallowSubclassFromPy]
  799. # We'll want to allow this at some point but right now we need to
  800. # disallow it because it doesn't work.
  801. class A:
  802. pass
  803. [file b.py]
  804. from native import A
  805. # It would be better if we disallowed it at class decl time but it is
  806. # really easy to do in __new__
  807. class B(A):
  808. pass
  809. [file driver.py]
  810. from b import B
  811. try:
  812. B()
  813. except TypeError:
  814. pass
  815. else:
  816. assert False, "instantiating was supposed to fail"
  817. [case testClassVariable]
  818. MYPY = False
  819. if MYPY:
  820. from typing import ClassVar
  821. class A:
  822. x = 10 # type: ClassVar[int]
  823. def g(x: int) -> None:
  824. A.x = 10
  825. def f() -> int:
  826. return A.x
  827. [file driver.py]
  828. from native import A, f
  829. assert f() == 10
  830. A.x = 200
  831. assert f() == 200
  832. [case testDefaultVars]
  833. from typing import Optional
  834. class A:
  835. x = 10
  836. w: object = 10
  837. def lol(self) -> None:
  838. self.x = 100
  839. LOL = 'lol'
  840. class B(A):
  841. y = LOL
  842. z = None # type: Optional[str]
  843. b = True
  844. bogus = None # type: int
  845. def g() -> None:
  846. a = A()
  847. assert a.x == 10
  848. a.x = 20
  849. assert a.x == 20
  850. b = B()
  851. assert b.x == 10
  852. b.x = 20
  853. assert b.x == 20
  854. assert b.y == 'lol'
  855. b.y = 'rofl'
  856. assert b.y == 'rofl'
  857. assert b.z is None
  858. [file driver.py]
  859. from native import *
  860. g()
  861. a = A()
  862. assert a.x == 10
  863. a.x = 20
  864. assert a.x == 20
  865. b = B()
  866. assert b.x == 10
  867. b.x = 20
  868. assert b.x == 20
  869. assert b.y == 'lol'
  870. b.y = 'rofl'
  871. assert b.y == 'rofl'
  872. assert b.z is None
  873. # N.B: this doesn't match cpython
  874. assert not hasattr(b, 'bogus')
  875. [case testProtocol]
  876. from typing_extensions import Protocol
  877. class Proto(Protocol):
  878. def foo(self, x: int) -> None:
  879. pass
  880. def bar(self, x: int) -> None:
  881. pass
  882. class A:
  883. def foo(self, x: int) -> None:
  884. print("A:", x)
  885. def bar(self, *args: int, **kwargs: int) -> None:
  886. print("A:", args, kwargs)
  887. class B(A, Proto):
  888. def foo(self, x: int) -> None:
  889. print("B:", x)
  890. def bar(self, *args: int, **kwargs: int) -> None:
  891. print("B:", args, kwargs)
  892. def f(x: Proto) -> None:
  893. x.foo(20)
  894. x.bar(x=20)
  895. [file driver.py]
  896. from native import A, B, f
  897. f(A())
  898. f(B())
  899. # ... this exploits a bug in glue methods to distinguish whether we
  900. # are making a direct call or a pycall...
  901. [out]
  902. A: 20
  903. A: () {'x': 20}
  904. B: 20
  905. B: (20,) {}
  906. [case testMethodOverrideDefault1]
  907. class A:
  908. def foo(self, x: int) -> None:
  909. pass
  910. class B(A):
  911. def foo(self, x: int, y: int = 10) -> None:
  912. print(x, y)
  913. def a(x: A) -> None:
  914. x.foo(1)
  915. def b(x: B) -> None:
  916. x.foo(2)
  917. x.foo(2, 3)
  918. [file driver.py]
  919. from native import B, a, b
  920. a(B())
  921. b(B())
  922. [out]
  923. 1 10
  924. 2 10
  925. 2 3
  926. [case testMethodOverrideDefault2]
  927. class A:
  928. def foo(self, *, x: int = -1) -> None:
  929. pass
  930. def bar(self, *, x: int = -1, y: int = -1) -> None:
  931. pass
  932. def baz(self, x: int = -1) -> None:
  933. pass
  934. class B(A):
  935. def foo(self, *, y: int = 0, x: int = 0) -> None:
  936. print(x, y)
  937. def bar(self, *, y: int = 0, x: int = 0) -> None:
  938. print(x, y)
  939. def baz(self, x: int = 0, *, y: int = 0) -> None:
  940. print(x, y)
  941. def a(x: A) -> None:
  942. x.foo(x=1)
  943. x.bar(x=1, y=2)
  944. x.bar(x=2, y=1)
  945. x.baz()
  946. x.baz(1)
  947. x.baz(x=2)
  948. [file driver.py]
  949. from native import B, a
  950. a(B())
  951. [out]
  952. 1 0
  953. 1 2
  954. 2 1
  955. 0 0
  956. 1 0
  957. 2 0
  958. [case testMethodOverrideDefault3]
  959. class A:
  960. @classmethod
  961. def foo(cls, *, x: int = 0) -> None:
  962. pass
  963. @staticmethod
  964. def bar(*, x: int = 0) -> None:
  965. pass
  966. @staticmethod
  967. def baz() -> object:
  968. pass
  969. class B(A):
  970. @classmethod
  971. def foo(cls, *, y: int = 0, x: int = 0) -> None:
  972. print(x, y)
  973. print(cls.__name__) # type: ignore
  974. @staticmethod
  975. def bar(*, y: int = 0, x: int = 0) -> None:
  976. print(x, y)
  977. @staticmethod
  978. def baz() -> int:
  979. return 10
  980. # This is just to make sure that this stuff works even when the
  981. # methods might be overridden.
  982. class C(B):
  983. @classmethod
  984. def foo(cls, *, y: int = 0, x: int = 0) -> None:
  985. pass
  986. @staticmethod
  987. def bar(*, y: int = 0, x: int = 0) -> None:
  988. pass
  989. @staticmethod
  990. def baz() -> int:
  991. return 10
  992. def a(x: A) -> None:
  993. x.foo(x=1)
  994. x.bar(x=1)
  995. print(x.baz())
  996. [file driver.py]
  997. from native import B, a
  998. a(B())
  999. [out]
  1000. 1 0
  1001. B
  1002. 1 0
  1003. 10
  1004. [case testMethodOverrideDefault4]
  1005. class Foo:
  1006. def f(self, x: int=20, *, z: int=10) -> None:
  1007. pass
  1008. class Bar(Foo):
  1009. def f(self, *args: int, **kwargs: int) -> None:
  1010. print("stuff", args, kwargs)
  1011. z: Foo = Bar()
  1012. z.f(1, z=50)
  1013. z.f()
  1014. [out]
  1015. stuff (1,) {'z': 50}
  1016. stuff () {}
  1017. [case testMethodOverrideDefault5]
  1018. from testutil import make_python_function
  1019. from mypy_extensions import mypyc_attr
  1020. from typing import TypeVar, Any
  1021. @mypyc_attr(allow_interpreted_subclasses=True)
  1022. class Foo:
  1023. def f(self, x: int=20, *, z: int=10) -> None:
  1024. print("Foo", x, z)
  1025. @make_python_function
  1026. def baz_f(self: Any, *args: int, **kwargs: int) -> None:
  1027. print("Baz", args, kwargs)
  1028. # Make an "interpreted" subtype of Foo
  1029. type2: Any = type
  1030. Bar = type2('Bar', (Foo,), {})
  1031. Baz = type2('Baz', (Foo,), {'f': baz_f})
  1032. y: Foo = Bar()
  1033. y.f(1, z=2)
  1034. y.f()
  1035. z: Foo = Baz()
  1036. z.f(1, z=2)
  1037. z.f()
  1038. [out]
  1039. Foo 1 2
  1040. Foo 20 10
  1041. Baz (1,) {'z': 2}
  1042. Baz () {}
  1043. [case testMethodOverrideDefault6]
  1044. from typing import Optional
  1045. class Foo:
  1046. def f(self, x: int=20) -> None:
  1047. pass
  1048. class Bar(Foo):
  1049. def f(self, x: Optional[int]=None) -> None:
  1050. print(x)
  1051. z: Foo = Bar()
  1052. z.f(1)
  1053. z.f()
  1054. [out]
  1055. 1
  1056. None
  1057. [case testMethodOverrideDefault7]
  1058. from typing import TypeVar, Any
  1059. class Foo:
  1060. def f(self, x: int, *args: int, **kwargs: int) -> None:
  1061. print("Foo", x, args, kwargs)
  1062. class Bar(Foo):
  1063. def f(self, *args: int, **kwargs: int) -> None:
  1064. print("Bar", args, kwargs)
  1065. z: Foo = Bar()
  1066. z.f(1, z=2)
  1067. z.f(1, 2, 3)
  1068. # z.f(x=5) # Not tested because we (knowingly) do the wrong thing and pass it as positional
  1069. [out]
  1070. Bar (1,) {'z': 2}
  1071. Bar (1, 2, 3) {}
  1072. --Bar () {'x': 5}
  1073. [case testMethodOverrideDefault8]
  1074. from typing import TypeVar, Any
  1075. class Foo:
  1076. def f(self, *args: int, **kwargs: int) -> None:
  1077. print("Foo", args, kwargs)
  1078. class Bar(Foo):
  1079. def f(self, x: int = 10, *args: int, **kwargs: int) -> None:
  1080. print("Bar", x, args, kwargs)
  1081. z: Foo = Bar()
  1082. z.f(1, z=2)
  1083. z.f(1, 2, 3)
  1084. z.f()
  1085. [out]
  1086. Bar 1 () {'z': 2}
  1087. Bar 1 (2, 3) {}
  1088. Bar 10 () {}
  1089. [case testMethodOverrideDefault9]
  1090. from testutil import make_python_function
  1091. from mypy_extensions import mypyc_attr
  1092. from typing import TypeVar, Any
  1093. @mypyc_attr(allow_interpreted_subclasses=True)
  1094. class Foo:
  1095. def f(self, x: int=20, y: int=40) -> None:
  1096. print("Foo", x, y)
  1097. # This sort of argument renaming is dodgy and not really sound but we
  1098. # shouldn't break it when they aren't actually used by name...
  1099. # (They *ought* to be positional only!)
  1100. @make_python_function
  1101. def baz_f(self, a: int=30, y: int=50) -> None:
  1102. print("Baz", a, y)
  1103. # Make an "interpreted" subtype of Foo
  1104. type2: Any = type
  1105. Baz = type2('Baz', (Foo,), {'f': baz_f})
  1106. z: Foo = Baz()
  1107. z.f()
  1108. z.f(y=1)
  1109. z.f(1, 2)
  1110. # Not tested because we don't (and probably won't) match cpython here
  1111. # from testutil import assertRaises
  1112. # with assertRaises(TypeError):
  1113. # z.f(x=7)
  1114. [out]
  1115. Baz 30 50
  1116. Baz 30 1
  1117. Baz 1 2
  1118. [case testOverride]
  1119. class A:
  1120. def f(self) -> int:
  1121. return 0
  1122. def g(self) -> int:
  1123. return 1
  1124. class B(A):
  1125. def g(self) -> int:
  1126. return 2
  1127. class C(B):
  1128. def f(self) -> int:
  1129. return 3
  1130. def test() -> None:
  1131. ba: A = B()
  1132. ca: A = C()
  1133. assert ba.f() == 0
  1134. assert ba.g() == 2
  1135. assert ca.f() == 3
  1136. assert ca.g() == 2
  1137. cc = C()
  1138. assert cc.f() == 3
  1139. assert cc.g() == 2
  1140. print('ok')
  1141. [file driver.py]
  1142. import native
  1143. native.test()
  1144. [out]
  1145. ok
  1146. [case testNoMetaclass]
  1147. from foo import Base
  1148. class Nothing(Base): # type: ignore
  1149. pass
  1150. [file foo.py]
  1151. from typing import Any
  1152. class Meta(type):
  1153. pass
  1154. class _Base(metaclass=Meta):
  1155. pass
  1156. Base = _Base # type: Any
  1157. [file driver.py]
  1158. try:
  1159. import native
  1160. except TypeError as e:
  1161. assert(str(e) == "mypyc classes can't have a metaclass")
  1162. [case testMetaclass]
  1163. from meta import Meta
  1164. class Nothing(metaclass=Meta):
  1165. pass
  1166. def ident(x): return x
  1167. @ident
  1168. class Test:
  1169. pass
  1170. [file meta.py]
  1171. class Meta(type):
  1172. def __new__(mcs, name, bases, dct):
  1173. dct['X'] = 10
  1174. return super().__new__(mcs, name, bases, dct)
  1175. [file driver.py]
  1176. from native import Nothing
  1177. assert Nothing.X == 10
  1178. [case testPickling]
  1179. from mypy_extensions import trait, mypyc_attr
  1180. from typing import Any, TypeVar, Generic
  1181. def dec(x: Any) -> Any:
  1182. return x
  1183. @mypyc_attr(allow_interpreted_subclasses=True)
  1184. class A:
  1185. x: int
  1186. y: str
  1187. @mypyc_attr(allow_interpreted_subclasses=True)
  1188. class B(A):
  1189. z: bool
  1190. def __init__(self, x: int, y: str, z: bool) -> None:
  1191. self.x = x
  1192. self.y = y
  1193. self.z = z
  1194. @trait
  1195. class T:
  1196. a: str
  1197. class C(B, T):
  1198. w: object
  1199. # property shouldn't go in
  1200. @property
  1201. def foo(self) -> int:
  1202. return 0
  1203. @dec
  1204. class D:
  1205. x: int
  1206. class E(D):
  1207. y: int
  1208. U = TypeVar('U')
  1209. class F(Generic[U]):
  1210. y: int
  1211. class G(F[int]):
  1212. pass
  1213. [file driver.py]
  1214. from native import A, B, T, C, D, E, F, G
  1215. import copy
  1216. import pickle
  1217. assert A.__mypyc_attrs__ == ('x', 'y')
  1218. assert B.__mypyc_attrs__ == ('z', 'x', 'y')
  1219. assert T.__mypyc_attrs__ == ('a',)
  1220. assert C.__mypyc_attrs__ == ('w', 'z', 'x', 'y', 'a')
  1221. assert not hasattr(D, '__mypyc_attrs__')
  1222. assert E.__mypyc_attrs__ == ('y', '__dict__')
  1223. assert F.__mypyc_attrs__ == ('y', '__dict__')
  1224. assert G.__mypyc_attrs__ == ('y', '__dict__')
  1225. b = B(10, '20', False)
  1226. assert b.__getstate__() == {'z': False, 'x': 10, 'y': '20'}
  1227. b2 = copy.copy(b)
  1228. assert b is not b2 and b.y == b2.y
  1229. b3 = pickle.loads(pickle.dumps(b))
  1230. assert b is not b3 and b.y == b3.y
  1231. e = E()
  1232. e.x = 10
  1233. e.y = 20
  1234. assert e.__getstate__() == {'y': 20, '__dict__': {'x': 10}}
  1235. e2 = pickle.loads(pickle.dumps(e))
  1236. assert e is not e2 and e.x == e2.x and e.y == e2.y
  1237. [case testInterpretedParentInit]
  1238. from interp import C
  1239. from typing import TypeVar
  1240. T = TypeVar('T')
  1241. def dec(x: T) -> T:
  1242. return x
  1243. @dec
  1244. class A:
  1245. def __init__(self, x: int) -> None:
  1246. self.x = x
  1247. class B(A):
  1248. s = 'test'
  1249. def b(x: int) -> B: return B(x)
  1250. class D(C):
  1251. s = 'test'
  1252. def d(x: int) -> D: return D(x)
  1253. [file interp.py]
  1254. class C:
  1255. def __init__(self, x: int) -> None:
  1256. self.x = x
  1257. [file driver.py]
  1258. from native import b, d, B, D
  1259. def test(f, v):
  1260. x = f(v)
  1261. assert x.x == v
  1262. assert x.s == 'test'
  1263. test(b, 20)
  1264. test(d, 30)
  1265. test(B, -1)
  1266. test(D, -2)
  1267. [case testInterpretedInherit]
  1268. from typing import TypeVar, Any, overload
  1269. from mypy_extensions import mypyc_attr, trait
  1270. T = TypeVar('T')
  1271. def dec(x: T) -> T: return x
  1272. @mypyc_attr(allow_interpreted_subclasses=True)
  1273. class Top:
  1274. def spam(self) -> str:
  1275. return "grandparent"
  1276. @mypyc_attr(allow_interpreted_subclasses=True)
  1277. @trait
  1278. class Trait:
  1279. def trait_method(self) -> str:
  1280. return "trait"
  1281. @mypyc_attr(allow_interpreted_subclasses=True)
  1282. class Foo(Top, Trait):
  1283. def __init__(self, x: int) -> None:
  1284. self.x = x
  1285. def foo(self) -> str:
  1286. return "parent foo: " + self.bar(self.x)
  1287. def bar(self, x: int) -> str:
  1288. return "parent bar: {}".format(x + self.x)
  1289. @dec
  1290. def decorated(self) -> str:
  1291. return "decorated parent"
  1292. @property
  1293. def read_property(self) -> str:
  1294. return "parent prop"
  1295. @overload
  1296. def overloaded(self, index: int) -> int: ...
  1297. @overload
  1298. def overloaded(self, index: str) -> str: ...
  1299. def overloaded(self, index: Any) -> Any:
  1300. return index
  1301. def foo(x: Foo) -> str:
  1302. return x.foo()
  1303. def bar(x: Foo, y: int) -> str:
  1304. return x.bar(y)
  1305. def spam(x: Top) -> str:
  1306. return x.spam()
  1307. def decorated(x: Foo) -> str:
  1308. return x.decorated()
  1309. def prop(x: Foo) -> str:
  1310. return x.read_property
  1311. def trait_method(x: Trait) -> str:
  1312. return x.trait_method()
  1313. def overloaded(x: Foo, s: str) -> str:
  1314. return x.overloaded(s)
  1315. [file interp.py]
  1316. from typing import Any
  1317. from native import Foo
  1318. class Bar(Foo):
  1319. def bar(self, x: int) -> str:
  1320. return "child bar: {}".format(x + self.x)
  1321. def spam(self) -> str:
  1322. assert super().spam() == "grandparent"
  1323. return "child"
  1324. @property
  1325. def read_property(self) -> str:
  1326. return "child prop"
  1327. def decorated(self) -> str:
  1328. return "decorated child"
  1329. def trait_method(self) -> str:
  1330. return "child"
  1331. def overloaded(self, index: Any) -> Any:
  1332. return index + index
  1333. class InterpBase:
  1334. def eggs(self) -> str:
  1335. return "eggs"
  1336. class Baz(InterpBase, Bar):
  1337. def __init__(self) -> None:
  1338. super().__init__(1000)
  1339. self.z = self.read_property
  1340. [file driver.py]
  1341. from native import Foo, foo, bar, spam, decorated, overloaded, prop, trait_method
  1342. from interp import Bar, Baz
  1343. from unittest.mock import patch
  1344. from testutil import assertRaises
  1345. x = Foo(10)
  1346. y = Bar(20)
  1347. z = Baz()
  1348. assert isinstance(y, Bar)
  1349. assert y.x == 20
  1350. assert y.bar(10) == "child bar: 30"
  1351. assert y.foo() == "parent foo: child bar: 40"
  1352. assert foo(y) == "parent foo: child bar: 40"
  1353. assert bar(y, 30) == "child bar: 50"
  1354. y.x = 30
  1355. assert bar(y, 30) == "child bar: 60"
  1356. assert spam(y) == "child"
  1357. assert y.read_property == "child prop"
  1358. assert prop(x) == "parent prop"
  1359. assert prop(y) == "child prop"
  1360. assert y.decorated() == "decorated child"
  1361. assert decorated(y) == "decorated child"
  1362. assert y.overloaded("test") == "testtest"
  1363. assert overloaded(y, "test") == "testtest"
  1364. assert y.trait_method() == "child"
  1365. assert trait_method(y) == "child"
  1366. assert z.bar(10) == "child bar: 1010"
  1367. assert bar(z, 10) == "child bar: 1010"
  1368. assert z.z == "child prop"
  1369. assert z.eggs() == "eggs"
  1370. with patch("interp.Bar.spam", lambda self: "monkey patched"):
  1371. assert y.spam() == "monkey patched"
  1372. spam(y) == "monkey patched"
  1373. with patch("interp.Bar.spam", lambda self: 20):
  1374. assert y.spam() == 20
  1375. with assertRaises(TypeError, "str object expected; got int"):
  1376. spam(y)
  1377. with assertRaises(TypeError, "int object expected; got str"):
  1378. y.x = "test"
  1379. [case testProperty]
  1380. from typing import Callable
  1381. from mypy_extensions import trait
  1382. class Temperature:
  1383. @property
  1384. def celsius(self) -> float:
  1385. return 5.0 * (self.fahrenheit - 32.0) / 9.0
  1386. def __init__(self, fahrenheit: float) -> None:
  1387. self.fahrenheit = fahrenheit
  1388. def print_temp(self) -> None:
  1389. print("F:", self.fahrenheit, "C:", self.celsius)
  1390. @property
  1391. def rankine(self) -> float:
  1392. raise NotImplementedError
  1393. class Access:
  1394. @property
  1395. def number_of_accesses(self) -> int:
  1396. self._count += 1
  1397. return self._count
  1398. def __init__(self) -> None:
  1399. self._count = 0
  1400. from typing import Callable
  1401. class BaseProperty:
  1402. @property
  1403. def doc(self) -> str:
  1404. return "Represents a sequence of values. Updates itself by next, which is a new value."
  1405. @property
  1406. def value(self) -> object:
  1407. return self._incrementer
  1408. @property
  1409. def bad_value(self) -> object:
  1410. return self._incrementer
  1411. @property
  1412. def next(self) -> BaseProperty:
  1413. return BaseProperty(self._incrementer + 1)
  1414. def __init__(self, value: int) -> None:
  1415. self._incrementer = value
  1416. class DerivedProperty(BaseProperty):
  1417. @property
  1418. def value(self) -> int:
  1419. return self._incrementer
  1420. @property
  1421. def bad_value(self) -> object:
  1422. return self._incrementer
  1423. def __init__(self, incr_func: Callable[[int], int], value: int) -> None:
  1424. BaseProperty.__init__(self, value)
  1425. self._incr_func = incr_func
  1426. @property
  1427. def next(self) -> DerivedProperty:
  1428. return DerivedProperty(self._incr_func, self._incr_func(self.value))
  1429. class AgainProperty(DerivedProperty):
  1430. @property
  1431. def next(self) -> AgainProperty:
  1432. return AgainProperty(self._incr_func, self._incr_func(self._incr_func(self.value)))
  1433. @property
  1434. def bad_value(self) -> int:
  1435. return self._incrementer
  1436. def print_first_n(n: int, thing: BaseProperty) -> None:
  1437. vals = []
  1438. cur_thing = thing
  1439. for _ in range(n):
  1440. vals.append(cur_thing.value)
  1441. cur_thing = cur_thing.next
  1442. print ('', vals)
  1443. @trait
  1444. class Trait:
  1445. @property
  1446. def value(self) -> int:
  1447. return 3
  1448. class Printer(Trait):
  1449. def print_value(self) -> None:
  1450. print(self.value)
  1451. [file driver.py]
  1452. from native import Temperature, Access
  1453. import traceback
  1454. x = Temperature(32.0)
  1455. try:
  1456. print (x.rankine)
  1457. except NotImplementedError as e:
  1458. traceback.print_exc()
  1459. print (x.celsius)
  1460. x.print_temp()
  1461. y = Temperature(212.0)
  1462. print (y.celsius)
  1463. y.print_temp()
  1464. z = Access()
  1465. print (z.number_of_accesses)
  1466. print (z.number_of_accesses)
  1467. print (z.number_of_accesses)
  1468. print (z.number_of_accesses)
  1469. from native import BaseProperty, DerivedProperty, AgainProperty, print_first_n
  1470. a = BaseProperty(7)
  1471. b = DerivedProperty((lambda x: x // 2 if (x % 2 == 0) else 3 * x + 1), 7)
  1472. c = AgainProperty((lambda x: x // 2 if (x % 2 == 0) else 3 * x + 1), 7)
  1473. def py_print_first_n(n: int, thing: BaseProperty) -> None:
  1474. vals = []
  1475. cur_thing = thing
  1476. for _ in range(n):
  1477. vals.append(cur_thing.value)
  1478. cur_thing = cur_thing.next
  1479. print ('', vals)
  1480. py_print_first_n(20, a)
  1481. py_print_first_n(20, b)
  1482. py_print_first_n(20, c)
  1483. print(a.next.next.next.bad_value)
  1484. print(b.next.next.next.bad_value)
  1485. print(c.next.next.next.bad_value)
  1486. print_first_n(20, a)
  1487. print_first_n(20, b)
  1488. print_first_n(20, c)
  1489. print (a.doc)
  1490. print (b.doc)
  1491. print (c.doc)
  1492. from native import Printer
  1493. Printer().print_value()
  1494. print (Printer().value)
  1495. [out]
  1496. Traceback (most recent call last):
  1497. File "driver.py", line 5, in <module>
  1498. print (x.rankine)
  1499. File "native.py", line 16, in rankine
  1500. raise NotImplementedError
  1501. NotImplementedError
  1502. 0.0
  1503. F: 32.0 C: 0.0
  1504. 100.0
  1505. F: 212.0 C: 100.0
  1506. 1
  1507. 2
  1508. 3
  1509. 4
  1510. [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
  1511. [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
  1512. [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
  1513. 10
  1514. 34
  1515. 26
  1516. [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
  1517. [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
  1518. [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
  1519. Represents a sequence of values. Updates itself by next, which is a new value.
  1520. Represents a sequence of values. Updates itself by next, which is a new value.
  1521. Represents a sequence of values. Updates itself by next, which is a new value.
  1522. 3
  1523. 3
  1524. [out version>=3.11]
  1525. Traceback (most recent call last):
  1526. File "driver.py", line 5, in <module>
  1527. print (x.rankine)
  1528. ^^^^^^^^^
  1529. File "native.py", line 16, in rankine
  1530. raise NotImplementedError
  1531. NotImplementedError
  1532. 0.0
  1533. F: 32.0 C: 0.0
  1534. 100.0
  1535. F: 212.0 C: 100.0
  1536. 1
  1537. 2
  1538. 3
  1539. 4
  1540. [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
  1541. [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
  1542. [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
  1543. 10
  1544. 34
  1545. 26
  1546. [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
  1547. [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
  1548. [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
  1549. Represents a sequence of values. Updates itself by next, which is a new value.
  1550. Represents a sequence of values. Updates itself by next, which is a new value.
  1551. Represents a sequence of values. Updates itself by next, which is a new value.
  1552. 3
  1553. 3
  1554. [case testPropertySetters]
  1555. from mypy_extensions import trait
  1556. class Foo():
  1557. def __init__(self) -> None:
  1558. self.attr = "unmodified"
  1559. class A:
  1560. def __init__(self) -> None:
  1561. self._x = 0
  1562. self._foo = Foo()
  1563. @property
  1564. def x(self) -> int:
  1565. return self._x
  1566. @x.setter
  1567. def x(self, val : int) -> None:
  1568. self._x = val
  1569. @property
  1570. def foo(self) -> Foo:
  1571. return self._foo
  1572. @foo.setter
  1573. def foo(self, val : Foo) -> None:
  1574. self._foo = val
  1575. # Overrides base property setters and getters
  1576. class B(A):
  1577. def __init__(self) -> None:
  1578. self._x = 10
  1579. @property
  1580. def x(self) -> int:
  1581. return self._x + 1
  1582. @x.setter
  1583. def x(self, val : int) -> None:
  1584. self._x = val + 1
  1585. # Inherits base property setters and getters
  1586. class C(A):
  1587. def __init__(self) -> None:
  1588. A.__init__(self)
  1589. @trait
  1590. class D():
  1591. def __init__(self) -> None:
  1592. self._x = 0
  1593. @property
  1594. def x(self) -> int:
  1595. return self._x
  1596. @x.setter
  1597. def x(self, val : int) -> None:
  1598. self._x = val
  1599. #Inherits trait property setters and getters
  1600. class E(D):
  1601. def __init__(self) -> None:
  1602. D.__init__(self)
  1603. #Overrides trait property setters and getters
  1604. class F(D):
  1605. def __init__(self) -> None:
  1606. self._x = 10
  1607. @property
  1608. def x(self) -> int:
  1609. return self._x + 10
  1610. @x.setter
  1611. def x(self, val : int) -> None:
  1612. self._x = val + 10
  1613. # # Property setter and getter are subtypes of base property setters and getters
  1614. # # class G(A):
  1615. # # def __init__(self) -> None:
  1616. # # A.__init__(self)
  1617. # # @property
  1618. # # def y(self) -> int:
  1619. # # return self._y
  1620. # # @y.setter
  1621. # # def y(self, val : object) -> None:
  1622. # # self._y = val
  1623. # No inheritance, just plain setter/getter
  1624. class G:
  1625. def __init__(self, x: int) -> None:
  1626. self._x = x
  1627. @property
  1628. def x(self) -> int:
  1629. return self._x
  1630. @x.setter
  1631. def x(self, x: int) -> None:
  1632. self._x = x
  1633. class H:
  1634. def __init__(self, g: G) -> None:
  1635. self.g = g
  1636. self.g.x = 5 # Should not be treated as initialization
  1637. [file other.py]
  1638. # Run in both interpreted and compiled mode
  1639. from native import A, B, C, D, E, F, G
  1640. a = A()
  1641. assert a.x == 0
  1642. assert a._x == 0
  1643. a.x = 1
  1644. assert a.x == 1
  1645. assert a._x == 1
  1646. a._x = 0
  1647. assert a.x == 0
  1648. assert a._x == 0
  1649. b = B()
  1650. assert b.x == 11
  1651. assert b._x == 10
  1652. b.x = 11
  1653. assert b.x == 13
  1654. b._x = 11
  1655. assert b.x == 12
  1656. c = C()
  1657. assert c.x == 0
  1658. c.x = 1000
  1659. assert c.x == 1000
  1660. e = E()
  1661. assert e.x == 0
  1662. e.x = 1000
  1663. assert e.x == 1000
  1664. f = F()
  1665. assert f.x == 20
  1666. f.x = 30
  1667. assert f.x == 50
  1668. g = G(4)
  1669. g.x = 20
  1670. assert g.x == 20
  1671. [file driver.py]
  1672. # Run the tests in both interpreted and compiled mode
  1673. import other
  1674. import other_interpreted
  1675. [out]
  1676. [case testAttributeOverridesProperty]
  1677. from typing import Any
  1678. from mypy_extensions import trait
  1679. @trait
  1680. class T1:
  1681. @property
  1682. def x(self) -> int: ...
  1683. @property
  1684. def y(self) -> int: ...
  1685. class C1(T1):
  1686. x: int = 1
  1687. y: int = 4
  1688. def test_read_only_property_in_trait_implemented_as_attribute() -> None:
  1689. c = C1()
  1690. c.x = 5
  1691. assert c.x == 5
  1692. assert c.y == 4
  1693. c.y = 6
  1694. assert c.y == 6
  1695. t: T1 = C1()
  1696. assert t.y == 4
  1697. t = c
  1698. assert t.x == 5
  1699. assert t.y == 6
  1700. a: Any = c
  1701. assert a.x == 5
  1702. assert a.y == 6
  1703. a.x = 7
  1704. a.y = 8
  1705. assert a.x == 7
  1706. assert a.y == 8
  1707. class B2:
  1708. @property
  1709. def x(self) -> int:
  1710. return 11
  1711. @property
  1712. def y(self) -> int:
  1713. return 25
  1714. class C2(B2):
  1715. x: int = 1
  1716. y: int = 4
  1717. def test_read_only_property_in_class_implemented_as_attribute() -> None:
  1718. c = C2()
  1719. c.x = 5
  1720. assert c.x == 5
  1721. assert c.y == 4
  1722. c.y = 6
  1723. assert c.y == 6
  1724. b: B2 = C2()
  1725. assert b.y == 4
  1726. b = c
  1727. assert b.x == 5
  1728. assert b.y == 6
  1729. a: Any = c
  1730. assert a.x == 5
  1731. assert a.y == 6
  1732. a.x = 7
  1733. a.y = 8
  1734. assert a.x == 7
  1735. assert a.y == 8
  1736. @trait
  1737. class T3:
  1738. @property
  1739. def x(self) -> int: ...
  1740. @property
  1741. def y(self) -> int: ...
  1742. class B3:
  1743. x: int = 1
  1744. y: int = 4
  1745. class C3(B3, T3):
  1746. pass
  1747. def test_read_only_property_implemented_as_attribute_indirectly() -> None:
  1748. c = C3()
  1749. c.x = 5
  1750. assert c.x == 5
  1751. assert c.y == 4
  1752. c.y = 6
  1753. assert c.y == 6
  1754. t: T3 = C3()
  1755. assert t.y == 4
  1756. t = c
  1757. assert t.x == 5
  1758. assert t.y == 6
  1759. a: Any = c
  1760. assert a.x == 5
  1761. assert a.y == 6
  1762. a.x = 7
  1763. a.y = 8
  1764. assert a.x == 7
  1765. assert a.y == 8
  1766. @trait
  1767. class T4:
  1768. @property
  1769. def x(self) -> int: ...
  1770. @x.setter
  1771. def x(self, v1: int) -> None: ...
  1772. @property
  1773. def y(self) -> int: ...
  1774. @y.setter
  1775. def y(self, v2: int) -> None: ...
  1776. class C4(T4):
  1777. x: int = 1
  1778. y: int = 4
  1779. def test_read_write_property_implemented_as_attribute() -> None:
  1780. c = C4()
  1781. c.x = 5
  1782. assert c.x == 5
  1783. assert c.y == 4
  1784. c.y = 6
  1785. assert c.y == 6
  1786. t: T4 = C4()
  1787. assert t.y == 4
  1788. t.x = 5
  1789. assert t.x == 5
  1790. t.y = 6
  1791. assert t.y == 6
  1792. a: Any = c
  1793. assert a.x == 5
  1794. assert a.y == 6
  1795. a.x = 7
  1796. a.y = 8
  1797. assert a.x == 7
  1798. assert a.y == 8
  1799. @trait
  1800. class T5:
  1801. @property
  1802. def x(self) -> int: ...
  1803. @x.setter
  1804. def x(self, v1: int) -> None: ...
  1805. @property
  1806. def y(self) -> int: ...
  1807. @y.setter
  1808. def y(self, v2: int) -> None: ...
  1809. class B5:
  1810. x: int = 1
  1811. y: int = 4
  1812. class BB5(B5):
  1813. pass
  1814. class C5(BB5, T5):
  1815. pass
  1816. def test_read_write_property_indirectly_implemented_as_attribute() -> None:
  1817. c = C5()
  1818. c.x = 5
  1819. assert c.x == 5
  1820. assert c.y == 4
  1821. c.y = 6
  1822. assert c.y == 6
  1823. t: T5 = C5()
  1824. assert t.y == 4
  1825. t.x = 5
  1826. assert t.x == 5
  1827. t.y = 6
  1828. assert t.y == 6
  1829. a: Any = c
  1830. assert a.x == 5
  1831. assert a.y == 6
  1832. a.x = 7
  1833. a.y = 8
  1834. assert a.x == 7
  1835. assert a.y == 8
  1836. [case testSubclassAttributeAccess]
  1837. from mypy_extensions import trait
  1838. class A:
  1839. v = 0
  1840. class B(A):
  1841. v = 1
  1842. class C(B):
  1843. v = 2
  1844. [file driver.py]
  1845. from native import A, B, C
  1846. a = A()
  1847. b = B()
  1848. c = C()
  1849. [case testCopyAlwaysDefinedAttributes]
  1850. import copy
  1851. from typing import Union
  1852. class A: pass
  1853. class C:
  1854. def __init__(self, n: int = 0) -> None:
  1855. self.n = n
  1856. self.s = ""
  1857. self.t = ("", 0)
  1858. self.u: Union[str, bytes] = ''
  1859. self.a = A()
  1860. def test_copy() -> None:
  1861. c1 = C()
  1862. c1.n = 1
  1863. c1.s = "x"
  1864. c2 = copy.copy(c1)
  1865. assert c2.n == 1
  1866. assert c2.s == "x"
  1867. assert c2.t == ("", 0)
  1868. assert c2.u == ''
  1869. assert c2.a is c1.a
  1870. [case testNonNativeCallsToDunderNewAndInit]
  1871. from typing import Any
  1872. from testutil import assertRaises
  1873. count_c = 0
  1874. class C:
  1875. def __init__(self) -> None:
  1876. self.x = 'a' # Always defined attribute
  1877. global count_c
  1878. count_c += 1
  1879. def get(self) -> str:
  1880. return self.x
  1881. def test_no_init_args() -> None:
  1882. global count_c
  1883. count_c = 0
  1884. # Use Any to get non-native semantics
  1885. cls: Any = C
  1886. # __new__ implicitly calls __init__ for native classes
  1887. obj = cls.__new__(cls)
  1888. assert obj.get() == 'a'
  1889. assert count_c == 1
  1890. # Make sure we don't call __init__ twice
  1891. obj2 = cls()
  1892. assert obj2.get() == 'a'
  1893. assert count_c == 2
  1894. count_d = 0
  1895. class D:
  1896. def __init__(self, x: str) -> None:
  1897. self.x = x # Always defined attribute
  1898. global count_d
  1899. count_d += 1
  1900. def get(self) -> str:
  1901. return self.x
  1902. def test_init_arg() -> None:
  1903. global count_d
  1904. count_d = 0
  1905. # Use Any to get non-native semantics
  1906. cls: Any = D
  1907. # __new__ implicitly calls __init__ for native classes
  1908. obj = cls.__new__(cls, 'abc')
  1909. assert obj.get() == 'abc'
  1910. assert count_d == 1
  1911. # Make sure we don't call __init__ twice
  1912. obj2 = cls('x')
  1913. assert obj2.get() == 'x'
  1914. assert count_d == 2
  1915. # Keyword args should work
  1916. obj = cls.__new__(cls, x='abc')
  1917. assert obj.get() == 'abc'
  1918. assert count_d == 3
  1919. def test_invalid_init_args() -> None:
  1920. # Use Any to get non-native semantics
  1921. cls: Any = D
  1922. with assertRaises(TypeError):
  1923. cls()
  1924. with assertRaises(TypeError):
  1925. cls(y='x')
  1926. with assertRaises(TypeError):
  1927. cls(1)
  1928. [case testTryDeletingAlwaysDefinedAttribute]
  1929. from typing import Any
  1930. from testutil import assertRaises
  1931. class C:
  1932. def __init__(self) -> None:
  1933. self.x = 0
  1934. class D(C):
  1935. pass
  1936. def test_try_deleting_always_defined_attr() -> None:
  1937. c: Any = C()
  1938. with assertRaises(AttributeError):
  1939. del c.x
  1940. d: Any = D()
  1941. with assertRaises(AttributeError):
  1942. del d.x
  1943. [case testAlwaysDefinedAttributeAndAllowInterpretedSubclasses]
  1944. from mypy_extensions import mypyc_attr
  1945. from m import define_interpreted_subclass
  1946. @mypyc_attr(allow_interpreted_subclasses=True)
  1947. class Base:
  1948. x = 5
  1949. y: int
  1950. def __init__(self, s: str) -> None:
  1951. self.s = s
  1952. class DerivedNative(Base):
  1953. def __init__(self) -> None:
  1954. super().__init__('x')
  1955. self.z = 3
  1956. def test_native_subclass() -> None:
  1957. o = DerivedNative()
  1958. assert o.x == 5
  1959. assert o.s == 'x'
  1960. assert o.z == 3
  1961. def test_interpreted_subclass() -> None:
  1962. define_interpreted_subclass(Base)
  1963. [file m.py]
  1964. from testutil import assertRaises
  1965. def define_interpreted_subclass(b):
  1966. class DerivedInterpreted1(b):
  1967. def __init__(self):
  1968. # Don't call base class __init__
  1969. pass
  1970. d1 = DerivedInterpreted1()
  1971. assert d1.x == 5
  1972. with assertRaises(AttributeError):
  1973. d1.y
  1974. with assertRaises(AttributeError):
  1975. d1.s
  1976. with assertRaises(AttributeError):
  1977. del d1.x
  1978. class DerivedInterpreted1(b):
  1979. def __init__(self):
  1980. super().__init__('y')
  1981. d2 = DerivedInterpreted1()
  1982. assert d2.x == 5
  1983. assert d2.s == 'y'
  1984. with assertRaises(AttributeError):
  1985. d2.y
  1986. with assertRaises(AttributeError):
  1987. del d2.x
  1988. [case testBaseClassSometimesDefinesAttribute]
  1989. class C:
  1990. def __init__(self, b: bool) -> None:
  1991. if b:
  1992. self.x = [1]
  1993. class D(C):
  1994. def __init__(self, b: bool) -> None:
  1995. super().__init__(b)
  1996. self.x = [2]
  1997. def test_base_class() -> None:
  1998. c = C(True)
  1999. assert c.x == [1]
  2000. c = C(False)
  2001. try:
  2002. c.x
  2003. except AttributeError:
  2004. return
  2005. assert False
  2006. def test_subclass() -> None:
  2007. d = D(True)
  2008. assert d.x == [2]
  2009. d = D(False)
  2010. assert d.x == [2]
  2011. [case testSerializableClass]
  2012. from mypy_extensions import mypyc_attr
  2013. from typing import Any
  2014. import copy
  2015. from testutil import assertRaises
  2016. @mypyc_attr(serializable=True)
  2017. class Base:
  2018. def __init__(self, s: str) -> None:
  2019. self.s = s
  2020. class Derived(Base):
  2021. def __init__(self, s: str, n: int) -> None:
  2022. super().__init__(s)
  2023. self.n = n
  2024. def test_copy_base() -> None:
  2025. o = Base('xyz')
  2026. o2 = copy.copy(o)
  2027. assert isinstance(o2, Base)
  2028. assert o2 is not o
  2029. assert o2.s == 'xyz'
  2030. def test_copy_derived() -> None:
  2031. d = Derived('xyz', 5)
  2032. d2 = copy.copy(d)
  2033. assert isinstance(d2, Derived)
  2034. assert d2 is not d
  2035. assert d2.s == 'xyz'
  2036. assert d2.n == 5
  2037. class NonSerializable:
  2038. def __init__(self, s: str) -> None:
  2039. self.s = s
  2040. @mypyc_attr(serializable=True)
  2041. class SerializableSub(NonSerializable):
  2042. def __init__(self, s: str, n: int) -> None:
  2043. super().__init__(s)
  2044. self.n = n
  2045. def test_serializable_sub_class() -> None:
  2046. n = NonSerializable('xyz')
  2047. assert n.s == 'xyz'
  2048. with assertRaises(TypeError):
  2049. copy.copy(n)
  2050. s = SerializableSub('foo', 6)
  2051. s2 = copy.copy(s)
  2052. assert s2 is not s
  2053. assert s2.s == 'foo'
  2054. assert s2.n == 6
  2055. def test_serializable_sub_class_call_new() -> None:
  2056. t: Any = SerializableSub
  2057. sub: SerializableSub = t.__new__(t)
  2058. with assertRaises(AttributeError):
  2059. sub.s
  2060. with assertRaises(AttributeError):
  2061. sub.n
  2062. base: NonSerializable = sub
  2063. with assertRaises(AttributeError):
  2064. base.s
  2065. [case testClassWithInherited__call__]
  2066. class Base:
  2067. def __call__(self) -> int:
  2068. return 1
  2069. class Derived(Base):
  2070. pass
  2071. assert Derived()() == 1
  2072. [case testClassWithFinalAttribute]
  2073. from typing_extensions import Final
  2074. class C:
  2075. A: Final = -1
  2076. a: Final = [A]
  2077. def test_final_attribute() -> None:
  2078. assert C.A == -1
  2079. assert C.a == [-1]