run-classes.test 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516
  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. import six
  1165. class Nothing1(metaclass=Meta):
  1166. pass
  1167. def ident(x): return x
  1168. @ident
  1169. class Test:
  1170. pass
  1171. class Nothing2(six.with_metaclass(Meta, Test)):
  1172. pass
  1173. @six.add_metaclass(Meta)
  1174. class Nothing3:
  1175. pass
  1176. [file meta.py]
  1177. from typing import Any
  1178. class Meta(type):
  1179. def __new__(mcs, name, bases, dct):
  1180. dct['X'] = 10
  1181. return super().__new__(mcs, name, bases, dct)
  1182. [file driver.py]
  1183. from native import Nothing1, Nothing2, Nothing3
  1184. assert Nothing1.X == 10
  1185. assert Nothing2.X == 10
  1186. assert Nothing3.X == 10
  1187. [case testPickling]
  1188. from mypy_extensions import trait, mypyc_attr
  1189. from typing import Any, TypeVar, Generic
  1190. def dec(x: Any) -> Any:
  1191. return x
  1192. @mypyc_attr(allow_interpreted_subclasses=True)
  1193. class A:
  1194. x: int
  1195. y: str
  1196. @mypyc_attr(allow_interpreted_subclasses=True)
  1197. class B(A):
  1198. z: bool
  1199. def __init__(self, x: int, y: str, z: bool) -> None:
  1200. self.x = x
  1201. self.y = y
  1202. self.z = z
  1203. @trait
  1204. class T:
  1205. a: str
  1206. class C(B, T):
  1207. w: object
  1208. # property shouldn't go in
  1209. @property
  1210. def foo(self) -> int:
  1211. return 0
  1212. @dec
  1213. class D:
  1214. x: int
  1215. class E(D):
  1216. y: int
  1217. U = TypeVar('U')
  1218. class F(Generic[U]):
  1219. y: int
  1220. class G(F[int]):
  1221. pass
  1222. [file driver.py]
  1223. from native import A, B, T, C, D, E, F, G
  1224. import copy
  1225. import pickle
  1226. assert A.__mypyc_attrs__ == ('x', 'y')
  1227. assert B.__mypyc_attrs__ == ('z', 'x', 'y')
  1228. assert T.__mypyc_attrs__ == ('a',)
  1229. assert C.__mypyc_attrs__ == ('w', 'z', 'x', 'y', 'a')
  1230. assert not hasattr(D, '__mypyc_attrs__')
  1231. assert E.__mypyc_attrs__ == ('y', '__dict__')
  1232. assert F.__mypyc_attrs__ == ('y', '__dict__')
  1233. assert G.__mypyc_attrs__ == ('y', '__dict__')
  1234. b = B(10, '20', False)
  1235. assert b.__getstate__() == {'z': False, 'x': 10, 'y': '20'}
  1236. b2 = copy.copy(b)
  1237. assert b is not b2 and b.y == b2.y
  1238. b3 = pickle.loads(pickle.dumps(b))
  1239. assert b is not b3 and b.y == b3.y
  1240. e = E()
  1241. e.x = 10
  1242. e.y = 20
  1243. assert e.__getstate__() == {'y': 20, '__dict__': {'x': 10}}
  1244. e2 = pickle.loads(pickle.dumps(e))
  1245. assert e is not e2 and e.x == e2.x and e.y == e2.y
  1246. [case testInterpretedParentInit]
  1247. from interp import C
  1248. from typing import TypeVar
  1249. T = TypeVar('T')
  1250. def dec(x: T) -> T:
  1251. return x
  1252. @dec
  1253. class A:
  1254. def __init__(self, x: int) -> None:
  1255. self.x = x
  1256. class B(A):
  1257. s = 'test'
  1258. def b(x: int) -> B: return B(x)
  1259. class D(C):
  1260. s = 'test'
  1261. def d(x: int) -> D: return D(x)
  1262. [file interp.py]
  1263. class C:
  1264. def __init__(self, x: int) -> None:
  1265. self.x = x
  1266. [file driver.py]
  1267. from native import b, d, B, D
  1268. def test(f, v):
  1269. x = f(v)
  1270. assert x.x == v
  1271. assert x.s == 'test'
  1272. test(b, 20)
  1273. test(d, 30)
  1274. test(B, -1)
  1275. test(D, -2)
  1276. [case testInterpretedInherit]
  1277. from typing import TypeVar, Any, overload
  1278. from mypy_extensions import mypyc_attr, trait
  1279. T = TypeVar('T')
  1280. def dec(x: T) -> T: return x
  1281. @mypyc_attr(allow_interpreted_subclasses=True)
  1282. class Top:
  1283. def spam(self) -> str:
  1284. return "grandparent"
  1285. @mypyc_attr(allow_interpreted_subclasses=True)
  1286. @trait
  1287. class Trait:
  1288. def trait_method(self) -> str:
  1289. return "trait"
  1290. @mypyc_attr(allow_interpreted_subclasses=True)
  1291. class Foo(Top, Trait):
  1292. def __init__(self, x: int) -> None:
  1293. self.x = x
  1294. def foo(self) -> str:
  1295. return "parent foo: " + self.bar(self.x)
  1296. def bar(self, x: int) -> str:
  1297. return "parent bar: {}".format(x + self.x)
  1298. @dec
  1299. def decorated(self) -> str:
  1300. return "decorated parent"
  1301. @property
  1302. def read_property(self) -> str:
  1303. return "parent prop"
  1304. @overload
  1305. def overloaded(self, index: int) -> int: ...
  1306. @overload
  1307. def overloaded(self, index: str) -> str: ...
  1308. def overloaded(self, index: Any) -> Any:
  1309. return index
  1310. def foo(x: Foo) -> str:
  1311. return x.foo()
  1312. def bar(x: Foo, y: int) -> str:
  1313. return x.bar(y)
  1314. def spam(x: Top) -> str:
  1315. return x.spam()
  1316. def decorated(x: Foo) -> str:
  1317. return x.decorated()
  1318. def prop(x: Foo) -> str:
  1319. return x.read_property
  1320. def trait_method(x: Trait) -> str:
  1321. return x.trait_method()
  1322. def overloaded(x: Foo, s: str) -> str:
  1323. return x.overloaded(s)
  1324. [file interp.py]
  1325. from typing import Any
  1326. from native import Foo
  1327. class Bar(Foo):
  1328. def bar(self, x: int) -> str:
  1329. return "child bar: {}".format(x + self.x)
  1330. def spam(self) -> str:
  1331. assert super().spam() == "grandparent"
  1332. return "child"
  1333. @property
  1334. def read_property(self) -> str:
  1335. return "child prop"
  1336. def decorated(self) -> str:
  1337. return "decorated child"
  1338. def trait_method(self) -> str:
  1339. return "child"
  1340. def overloaded(self, index: Any) -> Any:
  1341. return index + index
  1342. class InterpBase:
  1343. def eggs(self) -> str:
  1344. return "eggs"
  1345. class Baz(InterpBase, Bar):
  1346. def __init__(self) -> None:
  1347. super().__init__(1000)
  1348. self.z = self.read_property
  1349. [file driver.py]
  1350. from native import Foo, foo, bar, spam, decorated, overloaded, prop, trait_method
  1351. from interp import Bar, Baz
  1352. from unittest.mock import patch
  1353. from testutil import assertRaises
  1354. x = Foo(10)
  1355. y = Bar(20)
  1356. z = Baz()
  1357. assert isinstance(y, Bar)
  1358. assert y.x == 20
  1359. assert y.bar(10) == "child bar: 30"
  1360. assert y.foo() == "parent foo: child bar: 40"
  1361. assert foo(y) == "parent foo: child bar: 40"
  1362. assert bar(y, 30) == "child bar: 50"
  1363. y.x = 30
  1364. assert bar(y, 30) == "child bar: 60"
  1365. assert spam(y) == "child"
  1366. assert y.read_property == "child prop"
  1367. assert prop(x) == "parent prop"
  1368. assert prop(y) == "child prop"
  1369. assert y.decorated() == "decorated child"
  1370. assert decorated(y) == "decorated child"
  1371. assert y.overloaded("test") == "testtest"
  1372. assert overloaded(y, "test") == "testtest"
  1373. assert y.trait_method() == "child"
  1374. assert trait_method(y) == "child"
  1375. assert z.bar(10) == "child bar: 1010"
  1376. assert bar(z, 10) == "child bar: 1010"
  1377. assert z.z == "child prop"
  1378. assert z.eggs() == "eggs"
  1379. with patch("interp.Bar.spam", lambda self: "monkey patched"):
  1380. assert y.spam() == "monkey patched"
  1381. spam(y) == "monkey patched"
  1382. with patch("interp.Bar.spam", lambda self: 20):
  1383. assert y.spam() == 20
  1384. with assertRaises(TypeError, "str object expected; got int"):
  1385. spam(y)
  1386. with assertRaises(TypeError, "int object expected; got str"):
  1387. y.x = "test"
  1388. [case testProperty]
  1389. from typing import Callable
  1390. from mypy_extensions import trait
  1391. class Temperature:
  1392. @property
  1393. def celsius(self) -> float:
  1394. return 5.0 * (self.fahrenheit - 32.0) / 9.0
  1395. def __init__(self, fahrenheit: float) -> None:
  1396. self.fahrenheit = fahrenheit
  1397. def print_temp(self) -> None:
  1398. print("F:", self.fahrenheit, "C:", self.celsius)
  1399. @property
  1400. def rankine(self) -> float:
  1401. raise NotImplementedError
  1402. class Access:
  1403. @property
  1404. def number_of_accesses(self) -> int:
  1405. self._count += 1
  1406. return self._count
  1407. def __init__(self) -> None:
  1408. self._count = 0
  1409. from typing import Callable
  1410. class BaseProperty:
  1411. @property
  1412. def doc(self) -> str:
  1413. return "Represents a sequence of values. Updates itself by next, which is a new value."
  1414. @property
  1415. def value(self) -> object:
  1416. return self._incrementer
  1417. @property
  1418. def bad_value(self) -> object:
  1419. return self._incrementer
  1420. @property
  1421. def next(self) -> BaseProperty:
  1422. return BaseProperty(self._incrementer + 1)
  1423. def __init__(self, value: int) -> None:
  1424. self._incrementer = value
  1425. class DerivedProperty(BaseProperty):
  1426. @property
  1427. def value(self) -> int:
  1428. return self._incrementer
  1429. @property
  1430. def bad_value(self) -> object:
  1431. return self._incrementer
  1432. def __init__(self, incr_func: Callable[[int], int], value: int) -> None:
  1433. BaseProperty.__init__(self, value)
  1434. self._incr_func = incr_func
  1435. @property
  1436. def next(self) -> DerivedProperty:
  1437. return DerivedProperty(self._incr_func, self._incr_func(self.value))
  1438. class AgainProperty(DerivedProperty):
  1439. @property
  1440. def next(self) -> AgainProperty:
  1441. return AgainProperty(self._incr_func, self._incr_func(self._incr_func(self.value)))
  1442. @property
  1443. def bad_value(self) -> int:
  1444. return self._incrementer
  1445. def print_first_n(n: int, thing: BaseProperty) -> None:
  1446. vals = []
  1447. cur_thing = thing
  1448. for _ in range(n):
  1449. vals.append(cur_thing.value)
  1450. cur_thing = cur_thing.next
  1451. print ('', vals)
  1452. @trait
  1453. class Trait:
  1454. @property
  1455. def value(self) -> int:
  1456. return 3
  1457. class Printer(Trait):
  1458. def print_value(self) -> None:
  1459. print(self.value)
  1460. [file driver.py]
  1461. from native import Temperature, Access
  1462. import traceback
  1463. x = Temperature(32.0)
  1464. try:
  1465. print (x.rankine)
  1466. except NotImplementedError as e:
  1467. traceback.print_exc()
  1468. print (x.celsius)
  1469. x.print_temp()
  1470. y = Temperature(212.0)
  1471. print (y.celsius)
  1472. y.print_temp()
  1473. z = Access()
  1474. print (z.number_of_accesses)
  1475. print (z.number_of_accesses)
  1476. print (z.number_of_accesses)
  1477. print (z.number_of_accesses)
  1478. from native import BaseProperty, DerivedProperty, AgainProperty, print_first_n
  1479. a = BaseProperty(7)
  1480. b = DerivedProperty((lambda x: x // 2 if (x % 2 == 0) else 3 * x + 1), 7)
  1481. c = AgainProperty((lambda x: x // 2 if (x % 2 == 0) else 3 * x + 1), 7)
  1482. def py_print_first_n(n: int, thing: BaseProperty) -> None:
  1483. vals = []
  1484. cur_thing = thing
  1485. for _ in range(n):
  1486. vals.append(cur_thing.value)
  1487. cur_thing = cur_thing.next
  1488. print ('', vals)
  1489. py_print_first_n(20, a)
  1490. py_print_first_n(20, b)
  1491. py_print_first_n(20, c)
  1492. print(a.next.next.next.bad_value)
  1493. print(b.next.next.next.bad_value)
  1494. print(c.next.next.next.bad_value)
  1495. print_first_n(20, a)
  1496. print_first_n(20, b)
  1497. print_first_n(20, c)
  1498. print (a.doc)
  1499. print (b.doc)
  1500. print (c.doc)
  1501. from native import Printer
  1502. Printer().print_value()
  1503. print (Printer().value)
  1504. [out]
  1505. Traceback (most recent call last):
  1506. File "driver.py", line 5, in <module>
  1507. print (x.rankine)
  1508. File "native.py", line 16, in rankine
  1509. raise NotImplementedError
  1510. NotImplementedError
  1511. 0.0
  1512. F: 32.0 C: 0.0
  1513. 100.0
  1514. F: 212.0 C: 100.0
  1515. 1
  1516. 2
  1517. 3
  1518. 4
  1519. [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
  1520. [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
  1521. [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
  1522. 10
  1523. 34
  1524. 26
  1525. [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
  1526. [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
  1527. [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
  1528. Represents a sequence of values. Updates itself by next, which is a new value.
  1529. Represents a sequence of values. Updates itself by next, which is a new value.
  1530. Represents a sequence of values. Updates itself by next, which is a new value.
  1531. 3
  1532. 3
  1533. [out version>=3.11]
  1534. Traceback (most recent call last):
  1535. File "driver.py", line 5, in <module>
  1536. print (x.rankine)
  1537. ^^^^^^^^^
  1538. File "native.py", line 16, in rankine
  1539. raise NotImplementedError
  1540. NotImplementedError
  1541. 0.0
  1542. F: 32.0 C: 0.0
  1543. 100.0
  1544. F: 212.0 C: 100.0
  1545. 1
  1546. 2
  1547. 3
  1548. 4
  1549. [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
  1550. [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
  1551. [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
  1552. 10
  1553. 34
  1554. 26
  1555. [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
  1556. [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
  1557. [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
  1558. Represents a sequence of values. Updates itself by next, which is a new value.
  1559. Represents a sequence of values. Updates itself by next, which is a new value.
  1560. Represents a sequence of values. Updates itself by next, which is a new value.
  1561. 3
  1562. 3
  1563. [case testPropertySetters]
  1564. from mypy_extensions import trait
  1565. class Foo():
  1566. def __init__(self) -> None:
  1567. self.attr = "unmodified"
  1568. class A:
  1569. def __init__(self) -> None:
  1570. self._x = 0
  1571. self._foo = Foo()
  1572. @property
  1573. def x(self) -> int:
  1574. return self._x
  1575. @x.setter
  1576. def x(self, val : int) -> None:
  1577. self._x = val
  1578. @property
  1579. def foo(self) -> Foo:
  1580. return self._foo
  1581. @foo.setter
  1582. def foo(self, val : Foo) -> None:
  1583. self._foo = val
  1584. # Overrides base property setters and getters
  1585. class B(A):
  1586. def __init__(self) -> None:
  1587. self._x = 10
  1588. @property
  1589. def x(self) -> int:
  1590. return self._x + 1
  1591. @x.setter
  1592. def x(self, val : int) -> None:
  1593. self._x = val + 1
  1594. # Inherits base property setters and getters
  1595. class C(A):
  1596. def __init__(self) -> None:
  1597. A.__init__(self)
  1598. @trait
  1599. class D():
  1600. def __init__(self) -> None:
  1601. self._x = 0
  1602. @property
  1603. def x(self) -> int:
  1604. return self._x
  1605. @x.setter
  1606. def x(self, val : int) -> None:
  1607. self._x = val
  1608. #Inherits trait property setters and getters
  1609. class E(D):
  1610. def __init__(self) -> None:
  1611. D.__init__(self)
  1612. #Overrides trait property setters and getters
  1613. class F(D):
  1614. def __init__(self) -> None:
  1615. self._x = 10
  1616. @property
  1617. def x(self) -> int:
  1618. return self._x + 10
  1619. @x.setter
  1620. def x(self, val : int) -> None:
  1621. self._x = val + 10
  1622. # # Property setter and getter are subtypes of base property setters and getters
  1623. # # class G(A):
  1624. # # def __init__(self) -> None:
  1625. # # A.__init__(self)
  1626. # # @property
  1627. # # def y(self) -> int:
  1628. # # return self._y
  1629. # # @y.setter
  1630. # # def y(self, val : object) -> None:
  1631. # # self._y = val
  1632. # No inheritance, just plain setter/getter
  1633. class G:
  1634. def __init__(self, x: int) -> None:
  1635. self._x = x
  1636. @property
  1637. def x(self) -> int:
  1638. return self._x
  1639. @x.setter
  1640. def x(self, x: int) -> None:
  1641. self._x = x
  1642. class H:
  1643. def __init__(self, g: G) -> None:
  1644. self.g = g
  1645. self.g.x = 5 # Should not be treated as initialization
  1646. [file other.py]
  1647. # Run in both interpreted and compiled mode
  1648. from native import A, B, C, D, E, F, G
  1649. a = A()
  1650. assert a.x == 0
  1651. assert a._x == 0
  1652. a.x = 1
  1653. assert a.x == 1
  1654. assert a._x == 1
  1655. a._x = 0
  1656. assert a.x == 0
  1657. assert a._x == 0
  1658. b = B()
  1659. assert b.x == 11
  1660. assert b._x == 10
  1661. b.x = 11
  1662. assert b.x == 13
  1663. b._x = 11
  1664. assert b.x == 12
  1665. c = C()
  1666. assert c.x == 0
  1667. c.x = 1000
  1668. assert c.x == 1000
  1669. e = E()
  1670. assert e.x == 0
  1671. e.x = 1000
  1672. assert e.x == 1000
  1673. f = F()
  1674. assert f.x == 20
  1675. f.x = 30
  1676. assert f.x == 50
  1677. g = G(4)
  1678. g.x = 20
  1679. assert g.x == 20
  1680. [file driver.py]
  1681. # Run the tests in both interpreted and compiled mode
  1682. import other
  1683. import other_interpreted
  1684. [out]
  1685. [case testAttributeOverridesProperty]
  1686. from typing import Any
  1687. from mypy_extensions import trait
  1688. @trait
  1689. class T1:
  1690. @property
  1691. def x(self) -> int: ...
  1692. @property
  1693. def y(self) -> int: ...
  1694. class C1(T1):
  1695. x: int = 1
  1696. y: int = 4
  1697. def test_read_only_property_in_trait_implemented_as_attribute() -> None:
  1698. c = C1()
  1699. c.x = 5
  1700. assert c.x == 5
  1701. assert c.y == 4
  1702. c.y = 6
  1703. assert c.y == 6
  1704. t: T1 = C1()
  1705. assert t.y == 4
  1706. t = c
  1707. assert t.x == 5
  1708. assert t.y == 6
  1709. a: Any = c
  1710. assert a.x == 5
  1711. assert a.y == 6
  1712. a.x = 7
  1713. a.y = 8
  1714. assert a.x == 7
  1715. assert a.y == 8
  1716. class B2:
  1717. @property
  1718. def x(self) -> int:
  1719. return 11
  1720. @property
  1721. def y(self) -> int:
  1722. return 25
  1723. class C2(B2):
  1724. x: int = 1
  1725. y: int = 4
  1726. def test_read_only_property_in_class_implemented_as_attribute() -> None:
  1727. c = C2()
  1728. c.x = 5
  1729. assert c.x == 5
  1730. assert c.y == 4
  1731. c.y = 6
  1732. assert c.y == 6
  1733. b: B2 = C2()
  1734. assert b.y == 4
  1735. b = c
  1736. assert b.x == 5
  1737. assert b.y == 6
  1738. a: Any = c
  1739. assert a.x == 5
  1740. assert a.y == 6
  1741. a.x = 7
  1742. a.y = 8
  1743. assert a.x == 7
  1744. assert a.y == 8
  1745. @trait
  1746. class T3:
  1747. @property
  1748. def x(self) -> int: ...
  1749. @property
  1750. def y(self) -> int: ...
  1751. class B3:
  1752. x: int = 1
  1753. y: int = 4
  1754. class C3(B3, T3):
  1755. pass
  1756. def test_read_only_property_implemented_as_attribute_indirectly() -> None:
  1757. c = C3()
  1758. c.x = 5
  1759. assert c.x == 5
  1760. assert c.y == 4
  1761. c.y = 6
  1762. assert c.y == 6
  1763. t: T3 = C3()
  1764. assert t.y == 4
  1765. t = c
  1766. assert t.x == 5
  1767. assert t.y == 6
  1768. a: Any = c
  1769. assert a.x == 5
  1770. assert a.y == 6
  1771. a.x = 7
  1772. a.y = 8
  1773. assert a.x == 7
  1774. assert a.y == 8
  1775. @trait
  1776. class T4:
  1777. @property
  1778. def x(self) -> int: ...
  1779. @x.setter
  1780. def x(self, v1: int) -> None: ...
  1781. @property
  1782. def y(self) -> int: ...
  1783. @y.setter
  1784. def y(self, v2: int) -> None: ...
  1785. class C4(T4):
  1786. x: int = 1
  1787. y: int = 4
  1788. def test_read_write_property_implemented_as_attribute() -> None:
  1789. c = C4()
  1790. c.x = 5
  1791. assert c.x == 5
  1792. assert c.y == 4
  1793. c.y = 6
  1794. assert c.y == 6
  1795. t: T4 = C4()
  1796. assert t.y == 4
  1797. t.x = 5
  1798. assert t.x == 5
  1799. t.y = 6
  1800. assert t.y == 6
  1801. a: Any = c
  1802. assert a.x == 5
  1803. assert a.y == 6
  1804. a.x = 7
  1805. a.y = 8
  1806. assert a.x == 7
  1807. assert a.y == 8
  1808. @trait
  1809. class T5:
  1810. @property
  1811. def x(self) -> int: ...
  1812. @x.setter
  1813. def x(self, v1: int) -> None: ...
  1814. @property
  1815. def y(self) -> int: ...
  1816. @y.setter
  1817. def y(self, v2: int) -> None: ...
  1818. class B5:
  1819. x: int = 1
  1820. y: int = 4
  1821. class BB5(B5):
  1822. pass
  1823. class C5(BB5, T5):
  1824. pass
  1825. def test_read_write_property_indirectly_implemented_as_attribute() -> None:
  1826. c = C5()
  1827. c.x = 5
  1828. assert c.x == 5
  1829. assert c.y == 4
  1830. c.y = 6
  1831. assert c.y == 6
  1832. t: T5 = C5()
  1833. assert t.y == 4
  1834. t.x = 5
  1835. assert t.x == 5
  1836. t.y = 6
  1837. assert t.y == 6
  1838. a: Any = c
  1839. assert a.x == 5
  1840. assert a.y == 6
  1841. a.x = 7
  1842. a.y = 8
  1843. assert a.x == 7
  1844. assert a.y == 8
  1845. [case testSubclassAttributeAccess]
  1846. from mypy_extensions import trait
  1847. class A:
  1848. v = 0
  1849. class B(A):
  1850. v = 1
  1851. class C(B):
  1852. v = 2
  1853. [file driver.py]
  1854. from native import A, B, C
  1855. a = A()
  1856. b = B()
  1857. c = C()
  1858. [case testCopyAlwaysDefinedAttributes]
  1859. import copy
  1860. from typing import Union
  1861. class A: pass
  1862. class C:
  1863. def __init__(self, n: int = 0) -> None:
  1864. self.n = n
  1865. self.s = ""
  1866. self.t = ("", 0)
  1867. self.u: Union[str, bytes] = ''
  1868. self.a = A()
  1869. def test_copy() -> None:
  1870. c1 = C()
  1871. c1.n = 1
  1872. c1.s = "x"
  1873. c2 = copy.copy(c1)
  1874. assert c2.n == 1
  1875. assert c2.s == "x"
  1876. assert c2.t == ("", 0)
  1877. assert c2.u == ''
  1878. assert c2.a is c1.a
  1879. [case testNonNativeCallsToDunderNewAndInit]
  1880. from typing import Any
  1881. from testutil import assertRaises
  1882. count_c = 0
  1883. class C:
  1884. def __init__(self) -> None:
  1885. self.x = 'a' # Always defined attribute
  1886. global count_c
  1887. count_c += 1
  1888. def get(self) -> str:
  1889. return self.x
  1890. def test_no_init_args() -> None:
  1891. global count_c
  1892. count_c = 0
  1893. # Use Any to get non-native semantics
  1894. cls: Any = C
  1895. # __new__ implicitly calls __init__ for native classes
  1896. obj = cls.__new__(cls)
  1897. assert obj.get() == 'a'
  1898. assert count_c == 1
  1899. # Make sure we don't call __init__ twice
  1900. obj2 = cls()
  1901. assert obj2.get() == 'a'
  1902. assert count_c == 2
  1903. count_d = 0
  1904. class D:
  1905. def __init__(self, x: str) -> None:
  1906. self.x = x # Always defined attribute
  1907. global count_d
  1908. count_d += 1
  1909. def get(self) -> str:
  1910. return self.x
  1911. def test_init_arg() -> None:
  1912. global count_d
  1913. count_d = 0
  1914. # Use Any to get non-native semantics
  1915. cls: Any = D
  1916. # __new__ implicitly calls __init__ for native classes
  1917. obj = cls.__new__(cls, 'abc')
  1918. assert obj.get() == 'abc'
  1919. assert count_d == 1
  1920. # Make sure we don't call __init__ twice
  1921. obj2 = cls('x')
  1922. assert obj2.get() == 'x'
  1923. assert count_d == 2
  1924. # Keyword args should work
  1925. obj = cls.__new__(cls, x='abc')
  1926. assert obj.get() == 'abc'
  1927. assert count_d == 3
  1928. def test_invalid_init_args() -> None:
  1929. # Use Any to get non-native semantics
  1930. cls: Any = D
  1931. with assertRaises(TypeError):
  1932. cls()
  1933. with assertRaises(TypeError):
  1934. cls(y='x')
  1935. with assertRaises(TypeError):
  1936. cls(1)
  1937. [case testTryDeletingAlwaysDefinedAttribute]
  1938. from typing import Any
  1939. from testutil import assertRaises
  1940. class C:
  1941. def __init__(self) -> None:
  1942. self.x = 0
  1943. class D(C):
  1944. pass
  1945. def test_try_deleting_always_defined_attr() -> None:
  1946. c: Any = C()
  1947. with assertRaises(AttributeError):
  1948. del c.x
  1949. d: Any = D()
  1950. with assertRaises(AttributeError):
  1951. del d.x
  1952. [case testAlwaysDefinedAttributeAndAllowInterpretedSubclasses]
  1953. from mypy_extensions import mypyc_attr
  1954. from m import define_interpreted_subclass
  1955. @mypyc_attr(allow_interpreted_subclasses=True)
  1956. class Base:
  1957. x = 5
  1958. y: int
  1959. def __init__(self, s: str) -> None:
  1960. self.s = s
  1961. class DerivedNative(Base):
  1962. def __init__(self) -> None:
  1963. super().__init__('x')
  1964. self.z = 3
  1965. def test_native_subclass() -> None:
  1966. o = DerivedNative()
  1967. assert o.x == 5
  1968. assert o.s == 'x'
  1969. assert o.z == 3
  1970. def test_interpreted_subclass() -> None:
  1971. define_interpreted_subclass(Base)
  1972. [file m.py]
  1973. from testutil import assertRaises
  1974. def define_interpreted_subclass(b):
  1975. class DerivedInterpreted1(b):
  1976. def __init__(self):
  1977. # Don't call base class __init__
  1978. pass
  1979. d1 = DerivedInterpreted1()
  1980. assert d1.x == 5
  1981. with assertRaises(AttributeError):
  1982. d1.y
  1983. with assertRaises(AttributeError):
  1984. d1.s
  1985. with assertRaises(AttributeError):
  1986. del d1.x
  1987. class DerivedInterpreted1(b):
  1988. def __init__(self):
  1989. super().__init__('y')
  1990. d2 = DerivedInterpreted1()
  1991. assert d2.x == 5
  1992. assert d2.s == 'y'
  1993. with assertRaises(AttributeError):
  1994. d2.y
  1995. with assertRaises(AttributeError):
  1996. del d2.x
  1997. [case testBaseClassSometimesDefinesAttribute]
  1998. class C:
  1999. def __init__(self, b: bool) -> None:
  2000. if b:
  2001. self.x = [1]
  2002. class D(C):
  2003. def __init__(self, b: bool) -> None:
  2004. super().__init__(b)
  2005. self.x = [2]
  2006. def test_base_class() -> None:
  2007. c = C(True)
  2008. assert c.x == [1]
  2009. c = C(False)
  2010. try:
  2011. c.x
  2012. except AttributeError:
  2013. return
  2014. assert False
  2015. def test_subclass() -> None:
  2016. d = D(True)
  2017. assert d.x == [2]
  2018. d = D(False)
  2019. assert d.x == [2]
  2020. [case testSerializableClass]
  2021. from mypy_extensions import mypyc_attr
  2022. from typing import Any
  2023. import copy
  2024. from testutil import assertRaises
  2025. @mypyc_attr(serializable=True)
  2026. class Base:
  2027. def __init__(self, s: str) -> None:
  2028. self.s = s
  2029. class Derived(Base):
  2030. def __init__(self, s: str, n: int) -> None:
  2031. super().__init__(s)
  2032. self.n = n
  2033. def test_copy_base() -> None:
  2034. o = Base('xyz')
  2035. o2 = copy.copy(o)
  2036. assert isinstance(o2, Base)
  2037. assert o2 is not o
  2038. assert o2.s == 'xyz'
  2039. def test_copy_derived() -> None:
  2040. d = Derived('xyz', 5)
  2041. d2 = copy.copy(d)
  2042. assert isinstance(d2, Derived)
  2043. assert d2 is not d
  2044. assert d2.s == 'xyz'
  2045. assert d2.n == 5
  2046. class NonSerializable:
  2047. def __init__(self, s: str) -> None:
  2048. self.s = s
  2049. @mypyc_attr(serializable=True)
  2050. class SerializableSub(NonSerializable):
  2051. def __init__(self, s: str, n: int) -> None:
  2052. super().__init__(s)
  2053. self.n = n
  2054. def test_serializable_sub_class() -> None:
  2055. n = NonSerializable('xyz')
  2056. assert n.s == 'xyz'
  2057. with assertRaises(TypeError):
  2058. copy.copy(n)
  2059. s = SerializableSub('foo', 6)
  2060. s2 = copy.copy(s)
  2061. assert s2 is not s
  2062. assert s2.s == 'foo'
  2063. assert s2.n == 6
  2064. def test_serializable_sub_class_call_new() -> None:
  2065. t: Any = SerializableSub
  2066. sub: SerializableSub = t.__new__(t)
  2067. with assertRaises(AttributeError):
  2068. sub.s
  2069. with assertRaises(AttributeError):
  2070. sub.n
  2071. base: NonSerializable = sub
  2072. with assertRaises(AttributeError):
  2073. base.s
  2074. [case testClassWithInherited__call__]
  2075. class Base:
  2076. def __call__(self) -> int:
  2077. return 1
  2078. class Derived(Base):
  2079. pass
  2080. assert Derived()() == 1
  2081. [case testClassWithFinalAttribute]
  2082. from typing_extensions import Final
  2083. class C:
  2084. A: Final = -1
  2085. a: Final = [A]
  2086. def test_final_attribute() -> None:
  2087. assert C.A == -1
  2088. assert C.a == [-1]