Debian Codegraph @

mypyc/test-data/run-classes.test

raw
1 [case testEmptyClass]
2 class Empty: pass
3
4 def f(e: Empty) -> Empty:
5 return e
6
7 class EmptyEllipsis: ...
8
9 def g(e: EmptyEllipsis) -> EmptyEllipsis:
10 return e
11 [file driver.py]
12 from native import Empty, EmptyEllipsis, f, g
13
14 print(isinstance(Empty, type))
15 print(Empty)
16 print(str(Empty())[:20])
17
18 e = Empty()
19 print(f(e) is e)
20
21 print(isinstance(EmptyEllipsis, type))
22 print(EmptyEllipsis)
23 print(str(EmptyEllipsis())[:28])
24
25 e2 = EmptyEllipsis()
26 print(g(e2) is e2)
27 [out]
28 True
29 <class 'native.Empty'>
30 <native.Empty object
31 True
32 True
33 <class 'native.EmptyEllipsis'>
34 <native.EmptyEllipsis object
35 True
36
37 [case testClassWithFields]
38 class C:
39 x: int
40 y: int
41 z: 'D'
42 class D:
43 pass
44 [file driver.py]
45 from native import C
46 from testutil import assertRaises
47
48 c = C()
49 assert not hasattr(c, 'x')
50 assert not hasattr(c, 'y')
51 c.x = 1
52 c.y = 2
53 print(c.x)
54 print(c.y)
55 c.x = 10**30
56 print(c.x)
57 c.x = 10**30+1
58 print(c.x)
59 assert hasattr(c, 'x')
60 assert hasattr(c, 'y')
61 assert not hasattr(c, 'z')
62 with assertRaises(AttributeError, "'C' object attribute 'x' cannot be deleted"):
63 del c.x
64 assert hasattr(c, 'x')
65 assert hasattr(c, 'y')
66 with assertRaises(AttributeError, "'C' object attribute 'y' cannot be deleted"):
67 del c.y
68 assert hasattr(c, 'y')
69 c.x = 10**30+2
70 print(c.x)
71 assert hasattr(c, 'x')
72 [out]
73 1
74 2
75 1000000000000000000000000000000
76 1000000000000000000000000000001
77 1000000000000000000000000000002
78
79 [case testTypedDictWithFields]
80 import collections
81 import json
82 from typing import TypedDict
83 class C(TypedDict):
84 x: collections.deque
85 spam: json.JSONDecoder
86 [file driver.py]
87 from native import C
88 from collections import deque
89 from json import JSONDecoder
90
91 print(C.__annotations__["x"] is deque)
92 print(C.__annotations__["spam"] is JSONDecoder)
93 [typing fixtures/typing-full.pyi]
94 [out]
95 True
96 True
97
98 [case testTypedDictWithFieldsAs]
99 import json as _json
100 from typing import TypedDict
101
102 class C(TypedDict):
103 spam: _json.JSONDecoder
104 [file driver.py]
105 from native import C
106 from json import JSONDecoder
107
108 print(C.__annotations__["spam"] is JSONDecoder)
109 [typing fixtures/typing-full.pyi]
110 [out]
111 True
112
113 [case testTypedDictWithFieldsFrom]
114 from json import decoder
115 from typing import TypedDict
116
117 class C(TypedDict):
118 spam: decoder.JSONDecoder
119 [file driver.py]
120 from native import C
121 from json import JSONDecoder
122
123 print(C.__annotations__["spam"] is JSONDecoder)
124 [typing fixtures/typing-full.pyi]
125 [out]
126 True
127
128 [case testClassWithDeletableAttributes]
129 from typing import Any, cast
130 from testutil import assertRaises
131
132 class C:
133 __deletable__ = ['x', 'y']
134 x: int
135 y: int
136 z: int
137
138 def test_delete() -> None:
139 c = C()
140 c.x = 1
141 c.y = 2
142 c.z = 3
143 del c.x
144 del c.y
145 assert c.z == 3
146 with assertRaises(AttributeError, "attribute 'x' of 'C' undefined"):
147 c.x
148 with assertRaises(AttributeError, "attribute 'y' of 'C' undefined"):
149 c.y
150
151 def test_delete_any() -> None:
152 c: Any = C()
153 c.x = 1
154 c.y = 2
155 c.z = 3
156 del c.x
157 del c.y
158 with assertRaises(AttributeError, "'C' object attribute 'z' cannot be deleted"):
159 del c.z
160 assert c.z == 3
161 with assertRaises(AttributeError):
162 c.x
163 with assertRaises(AttributeError):
164 c.y
165
166 class Base:
167 __deletable__ = ['a']
168 a: int
169 b: int
170
171 class Deriv(Base):
172 __deletable__ = ('c',)
173 c: str
174 d: str
175
176 def test_delete_with_inheritance() -> None:
177 d = Deriv()
178 d.a = 0
179 d.b = 1
180 d.c = 'X'
181 d.d = 'Y'
182 del d.a
183 with assertRaises(AttributeError):
184 d.a
185 del d.c
186 with assertRaises(AttributeError):
187 d.c
188 assert d.b == 1
189 assert d.d == 'Y'
190
191 def test_delete_with_inheritance_any() -> None:
192 d: Any = Deriv()
193 d.a = 0
194 d.b = 1
195 d.c = 'X'
196 d.d = 'Y'
197 del d.a
198 with assertRaises(AttributeError):
199 d.a
200 del d.c
201 with assertRaises(AttributeError):
202 d.c
203 with assertRaises(AttributeError):
204 del d.b
205 assert d.b == 1
206 with assertRaises(AttributeError):
207 del d.d
208 assert d.d == 'Y'
209
210 def decorator(cls):
211 return cls
212
213 @decorator
214 class NonExt:
215 x: int
216 y: int
217
218 # No effect in a non-native class
219 __deletable__ = ['x']
220
221 def test_non_ext() -> None:
222 n = NonExt()
223 n.x = 2
224 n.y = 3
225 del n.x
226 del n.y
227 with assertRaises(AttributeError):
228 n.x
229 with assertRaises(AttributeError):
230 n.y
231
232 def test_non_ext_any() -> None:
233 n: Any = NonExt()
234 n.x = 2
235 n.y = 3
236 del n.x
237 del n.y
238 with assertRaises(AttributeError):
239 n.x
240 with assertRaises(AttributeError):
241 n.y
242
243 [case testNonExtMisc]
244 from typing import Any, overload
245
246 def decorator(cls) -> Any:
247 return cls
248
249 @decorator
250 class C:
251 def __init__(self) -> None:
252 self.c = 3
253
254 def get_c(self) -> int:
255 return self.c
256
257 @decorator
258 class B(C):
259 def __init__(self) -> None:
260 super().__init__()
261 self.b = 2
262
263 def get_b(self) -> int:
264 return self.b
265
266 @decorator
267 class A(B):
268 def __init__(self) -> None:
269 super().__init__()
270 self.a = 1
271
272 @classmethod
273 def constant(cls) -> int:
274 return 4
275
276 def get_a(self) -> int:
277 return self.a
278
279 @decorator
280 class Overload:
281 @overload
282 def get(self, index: int) -> int: ...
283
284 @overload
285 def get(self, index: str) -> str: ...
286
287 def get(self, index: Any) -> Any:
288 return index
289
290 def get(c: Overload, s: str) -> str:
291 return c.get(s)
292
293 @decorator
294 class Var:
295 x = 'xy'
296
297 def get_class_var() -> str:
298 return Var.x
299
300 [file driver.py]
301 from native import A, Overload, get, get_class_var
302 a = A()
303 assert a.a == 1
304 assert a.b == 2
305 assert a.c == 3
306 assert a.get_a() == 1
307 assert a.get_b() == 2
308 assert a.get_c() == 3
309 assert A.constant() == 4
310
311 o = Overload()
312 assert get(o, "test") == "test"
313 assert o.get(20) == 20
314
315 assert get_class_var() == 'xy'
316
317 [case testEnum]
318 from enum import Enum
319
320 class TestEnum(Enum):
321 _order_ = "a b"
322 a = 1
323 b = 2
324
325 @classmethod
326 def test(cls) -> int:
327 return 3
328
329 assert TestEnum.test() == 3
330
331 import enum
332
333 class Pokemon(enum.Enum):
334 magikarp = 1
335 squirtle = 2
336 slowbro = 3
337
338 assert Pokemon.magikarp.value == 1
339 assert Pokemon.squirtle.name == 'squirtle'
340
341 [file other.py]
342 # Force a multi-module test to make sure we can compile multi-file with
343 # non-extension classes
344
345 [file driver.py]
346 import sys
347 # "_order_" isn't supported in 3.5
348 if sys.version_info[:2] > (3, 5):
349 from native import TestEnum
350 assert TestEnum.a.name == 'a'
351 assert TestEnum.a.value == 1
352 assert TestEnum.b.name == 'b'
353 assert TestEnum.b.value == 2
354
355 [case testRunSuperYieldFromDict]
356 from typing import Any, Iterator
357
358 class DictSubclass(dict):
359 def items(self) -> Iterator[Any]:
360 yield 1
361 yield from super().items()
362
363 def test_sub_dict() -> None:
364 assert list(DictSubclass().items()) == [1]
365
366 [case testGetAttribute]
367 class C:
368 x: int
369 y: int
370
371 def getx(c: C) -> int:
372 return c.x
373
374 def gety(c: C) -> int:
375 return c.y
376 [file driver.py]
377 from native import C, getx, gety
378 c = C()
379 c.x = 10**30
380 c.y = 10**30 + 1
381 print(getx(c))
382 print(gety(c))
383 [out]
384 1000000000000000000000000000000
385 1000000000000000000000000000001
386
387 [case testSetAttribute]
388 class C:
389 x: int
390 y: int
391
392 def setx(c: C, v: int) -> None:
393 c.x = v
394
395 def sety(c: C, v: int) -> None:
396 c.y = v
397 [file driver.py]
398 from native import C, setx, sety
399 c = C()
400 setx(c, 10**30)
401 sety(c, 10**30 + 1)
402 print(c.x)
403 print(c.y)
404 setx(c, 4)
405 sety(c, 5)
406 print(c.x, c.y)
407 setx(c, 10**30 + 2)
408 sety(c, 10**30 + 3)
409 print(c.x)
410 print(c.y)
411 [out]
412 1000000000000000000000000000000
413 1000000000000000000000000000001
414 4 5
415 1000000000000000000000000000002
416 1000000000000000000000000000003
417
418 [case testAttributeTypes]
419 from typing import List, Tuple
420 class C:
421 a: List[int]
422 b: bool
423 c: C
424 d: object
425 e: int
426
427 def setattrs(o: C, a: List[int], b: bool, c: C) -> None:
428 o.a = a
429 o.b = b
430 o.c = c
431
432 def getattrs(o: C) -> Tuple[List[int], bool, C]:
433 return o.a, o.b, o.c
434 [file driver.py]
435 from native import C, setattrs, getattrs
436 from testutil import assertRaises
437
438 c1 = C()
439 c2 = C()
440 aa = [2]
441 setattrs(c1, aa, True, c2)
442 a, b, c = getattrs(c1)
443 assert a is aa
444 assert b is True
445 assert c is c2
446
447 o = object()
448 c1.d = o
449 assert c1.d is o
450
451 c3 = C()
452 with assertRaises(AttributeError, "attribute 'a' of 'C' undefined"):
453 c3.a
454 with assertRaises(AttributeError, "attribute 'b' of 'C' undefined"):
455 c3.b
456 with assertRaises(AttributeError, "attribute 'c' of 'C' undefined"):
457 c3.c
458 with assertRaises(AttributeError, "attribute 'd' of 'C' undefined"):
459 c3.d
460 with assertRaises(AttributeError, "attribute 'e' of 'C' undefined"):
461 c3.e
462
463 [case testInitMethodWithMissingNoneReturnAnnotation]
464 class C:
465 def __init__(self):
466 self.x = 42
467 [file driver.py]
468 from native import C
469 c = C()
470 assert c is not None
471 assert c.x == 42
472
473 [case testConstructClassWithDefaultConstructor]
474 class C:
475 a: int
476 b: int
477
478 def f() -> C:
479 c = C()
480 c.a = 13
481 return c
482 [file driver.py]
483 from native import f, C
484 c = f()
485 assert c.a == 13
486 assert type(c) == C
487 assert not hasattr(c, 'b')
488
489 [case testCastUserClass]
490 from typing import List
491
492 class C:
493 x: int
494
495 def f(a: List[C]) -> C:
496 return a[0]
497 [file driver.py]
498 from native import f, C
499 c = C()
500 assert f([c]) is c
501
502 [case testClass1]
503 class A:
504 def __init__(self, x: int) -> None:
505 self.x = x
506 def foo(self) -> int:
507 return self.x+1
508 def foo() -> int:
509 a = A(20)
510 return a.foo()
511 [file driver.py]
512 from native import A, foo
513 a = A(10)
514 assert a.foo() == 11
515 assert foo() == 21
516
517 [case testClassKwargs]
518 class X:
519 def __init__(self, msg: str, **variables: int) -> None:
520 self.msg = msg
521 self.variables = variables
522
523 [file driver.py]
524 import traceback
525 from native import X
526 x = X('hello', a=0, b=1)
527 assert x.msg == 'hello'
528 assert x.variables == {'a': 0, 'b': 1}
529 try:
530 X('hello', msg='hello')
531 except TypeError as e:
532 print(f"{type(e).__name__}: {e}")
533 [out]
534 TypeError: argument for __init__() given by name ('msg') and position (1)
535
536 [case testGenericClass]
537 from typing import TypeVar, Generic, Sequence
538 T = TypeVar('T')
539 class C(Generic[T]):
540 x: T
541 def __init__(self, x: T) -> None:
542 self.x = x
543 def get(self) -> T:
544 return self.x
545 def set(self, y: T) -> None:
546 self.x = y
547
548 # Test subclassing generic classes both with and without a generic param
549 class A(Sequence[int]):
550 pass
551 class B(Sequence[T]):
552 pass
553
554 def f(c: C[int]) -> int:
555 y = c.get()
556 d = C[int](2)
557 c.set(c.get() + 1 + d.get())
558 c.x = c.x + 2
559 return c.x
560
561 [file driver.py]
562 from native import C, f
563 c = C(6)
564 assert f(c) == 11
565 c.x = 'x'
566 assert c.x == 'x'
567 c.set([1])
568 assert c.x == [1]
569 assert c.get() == [1]
570
571 [case testSubclass1]
572 from typing import Tuple
573
574 class A:
575 def __init__(self) -> None:
576 self.x = 10
577 def hi(self, suffix: str) -> str:
578 return str(self.x) + suffix
579 class B(A):
580 def __init__(self) -> None:
581 self.x = 20
582 self.y = 'world'
583 def hi(self, suffix: str) -> str:
584 return 'hello ' + str(self.y) + suffix
585
586 def use_a(x: A) -> Tuple[int, str]:
587 return (x.x, x.hi(''))
588 def use_b(x: B) -> str:
589 return x.hi('')
590
591 [file driver.py]
592 from native import A, B, use_a, use_b
593 a = A()
594 b = B()
595 assert use_a(a) == (10, '10')
596 assert use_a(b) == (20, 'hello world')
597 assert a.x == 10
598 assert b.x == 20
599 assert b.y == 'world'
600 assert a.hi('!') == '10!'
601 assert b.hi('!') == 'hello world!'
602 assert use_b(b) == 'hello world'
603
604 [case testSubclassSpecialize1]
605 class A:
606 def foo(self, x: int) -> object:
607 print('A')
608 return str(x)
609 def bar(self, x: int) -> None:
610 print(x + 1)
611 class B(A):
612 def foo(self, x: object) -> int:
613 print('B')
614 return id(x)
615 def bar(self, x: object) -> None:
616 print(x)
617
618 def use_a(x: A, y: int) -> object:
619 x.bar(10)
620 return x.foo(y)
621
622 def use_b(x: B, y: object) -> int:
623 return x.foo(y)
624
625 [file driver.py]
626 from native import A, B, use_a, use_b
627 a = A()
628 b = B()
629 o = object()
630 i = 10
631 assert a.foo(10) == '10'
632 assert b.foo(o) == id(o)
633 assert use_a(a, 10) == '10'
634 assert use_b(b, o) == id(o)
635 assert use_a(b, i) == id(i)
636 [out]
637 A
638 B
639 11
640 A
641 B
642 10
643 B
644
645 [case testSubclassSpecialize2]
646 class A:
647 def foo(self, x: int) -> object:
648 print('A')
649 return str(x)
650 class B(A):
651 def foo(self, x: object) -> object:
652 print('B')
653 return x
654 class C(B):
655 def foo(self, x: object) -> int:
656 print('C')
657 return id(x)
658
659 def use_a(x: A, y: int) -> object:
660 return x.foo(y)
661
662 def use_b(x: B, y: object) -> object:
663 return x.foo(y)
664
665 def use_c(x: C, y: object) -> int:
666 return x.foo(y)
667
668 [file driver.py]
669 from native import A, B, C, use_a, use_b, use_c
670 a = A()
671 b = B()
672 c = C()
673 o = object()
674 i = 10
675 assert a.foo(10) == '10'
676 assert b.foo(o) == o
677 assert c.foo(o) == id(o)
678 assert use_a(a, 10) == '10'
679 assert use_a(b, i) is i
680 assert use_a(c, i) == id(i)
681 assert use_b(b, o) == o
682 assert use_b(c, o) == id(o)
683 assert use_c(c, o) == id(o)
684 [out]
685 A
686 B
687 C
688 A
689 B
690 C
691 B
692 C
693 C
694
695 [case testIsInstance]
696 from typing import Optional
697 class X: pass
698 class A(X): pass
699 class B(A): pass
700
701 def isa(x: object) -> bool:
702 return isinstance(x, A)
703 def isint(x: object) -> bool:
704 return isinstance(x, int)
705 def isstr(x: object) -> bool:
706 return isinstance(x, str)
707 def islist(x: object) -> bool:
708 return isinstance(x, list)
709 def ist(x: object, t: object) -> bool: # TODO: Second argument should be 'type'
710 return isinstance(x, t)
711 def pointless(x: Optional[X]) -> str:
712 if isinstance(x, A):
713 return str(x)
714 return ''
715 [file driver.py]
716 from native import X, A, B, isa, isint, isstr, islist, ist
717 assert isa(1) == False
718 assert isa(A()) == True
719 assert isa(B()) == True
720 assert isa(X()) == False
721
722 assert isint(1) == True
723 assert isint('') == False
724 assert isint(A()) == False
725
726 assert isstr(1) == False
727 assert isstr('') == True
728
729 assert islist(1) == False
730 assert islist([]) == True
731
732 assert ist(1, int) == True
733 assert ist(1, str) == False
734 try:
735 ist(1, 2)
736 except TypeError:
737 pass
738 else:
739 assert False
740
741 [case testSubclassUninitAttr]
742 class X:
743 x: int
744 class A(X):
745 pass
746 [file driver.py]
747 import traceback
748 from native import A
749 try:
750 A().x
751 except AttributeError:
752 traceback.print_exc()
753 [out]
754 Traceback (most recent call last):
755 File "driver.py", line 4, in <module>
756 A().x
757 AttributeError: attribute 'x' of 'X' undefined
758
759 [case testClassMethods]
760 from typing import ClassVar, Any, final
761 from mypy_extensions import mypyc_attr
762
763 from interp import make_interpreted_subclass
764
765 class C:
766 lurr: ClassVar[int] = 9
767 @staticmethod
768 def foo(x: int) -> int:
769 return 10 + x
770 @classmethod
771 def bar(cls, x: int) -> int:
772 return cls.lurr + x
773 @staticmethod
774 def baz(x: int, y: int = 10) -> int:
775 return y - x
776 @classmethod
777 def quux(cls, x: int, y: int = 10) -> int:
778 return y - x
779 @classmethod
780 def call_other(cls, x: int) -> int:
781 return cls.quux(x, 3)
782
783 class D(C):
784 def f(self) -> int:
785 return super().foo(1) + super().bar(2) + super().baz(10) + super().quux(10)
786
787 def ctest1() -> int:
788 return C.foo(1) + C.bar(2) + C.baz(10) + C.quux(10) + C.quux(y=10, x=9)
789
790 def ctest2() -> int:
791 c = C()
792 return c.foo(1) + c.bar(2) + c.baz(10)
793
794 CAny: Any = C
795
796 def test_classmethod_using_any() -> None:
797 assert CAny.foo(10) == 20
798 assert CAny.bar(10) == 19
799
800 def test_classmethod_on_instance() -> None:
801 c = C()
802 assert c.foo(10) == 20
803 assert c.bar(10) == 19
804 assert c.call_other(1) == 2
805
806 def test_classmethod_misc() -> None:
807 assert ctest1() == 23
808 assert ctest2() == 22
809 assert C.call_other(2) == 1
810
811 def test_classmethod_using_super() -> None:
812 d = D()
813 assert d.f() == 22
814
815 @final
816 class F1:
817 @classmethod
818 def f(cls, x: int) -> int:
819 return cls.g(x)
820
821 @classmethod
822 def g(cls, x: int) -> int:
823 return x + 1
824
825 class F2: # Implicitly final (no subclasses)
826 @classmethod
827 def f(cls, x: int) -> int:
828 return cls.g(x)
829
830 @classmethod
831 def g(cls, x: int) -> int:
832 return x + 1
833
834 def test_classmethod_of_final_class() -> None:
835 assert F1.f(5) == 6
836 assert F2.f(7) == 8
837
838 @mypyc_attr(allow_interpreted_subclasses=True)
839 class CI:
840 @classmethod
841 def f(cls, x: int) -> int:
842 return cls.g(x)
843
844 @classmethod
845 def g(cls, x: int) -> int:
846 return x + 1
847
848 def test_classmethod_with_allow_interpreted() -> None:
849 assert CI.f(4) == 5
850 sub = make_interpreted_subclass(CI)
851 assert sub.f(4) == 7
852
853 [file interp.py]
854 def make_interpreted_subclass(base):
855 class Sub(base): # type: ignore[misc, valid-type]
856 @classmethod
857 def g(cls, x: int) -> int:
858 return x + 3
859 return Sub
860
861 [case testSuper]
862 from mypy_extensions import trait
863 from typing import List
864
865 class A:
866 def __init__(self, x: int) -> None:
867 self.x = x
868
869 def foo(self, x: int) -> int:
870 return x
871
872 class B(A):
873 def __init__(self, x: int, y: int) -> None:
874 super().__init__(x)
875 self.y = y
876
877 def foo(self, x: int) -> int:
878 return super().foo(x+1)
879
880 class C(B):
881 def __init__(self, x: int, y: int) -> None:
882 super(C, self).__init__(x, y + 1)
883
884 def foo(self, x: int) -> int:
885 # should go to A, not B
886 return super(B, self).foo(x+1)
887
888 class X:
889 def __init__(self, x: int) -> None:
890 self.x = x
891 class Y(X):
892 pass
893 class Z(Y):
894 def __init__(self, x: int, y: int) -> None:
895 super().__init__(x)
896 self.y = y
897
898 @trait
899 class T:
900 def v_int(self, x: int) -> None: pass
901 def v_list(self, x: List[int]) -> None:
902 if x:
903 self.v_int(x[0])
904 self.v_list(x[1:])
905
906 class PrintList(T):
907 def v_int(self, x: int) -> None:
908 print(x)
909 def v_list(self, x: List[int]) -> None:
910 print('yo!')
911 super().v_list(x)
912
913 [file driver.py]
914 import traceback
915 from native import *
916 b = B(10, 20)
917 assert b.x == 10 and b.y == 20
918 c = C(10, 20)
919 assert c.x == 10 and c.y == 21
920 z = Z(10, 20)
921 assert z.x == 10 and z.y == 20
922
923 assert c.foo(10) == 11
924
925 PrintList().v_list([1,2,3])
926 [out]
927 yo!
928 1
929 yo!
930 2
931 yo!
932 3
933 yo!
934
935 [case testSubclassException]
936 class Failure(Exception):
937 def __init__(self, x: int) -> None:
938 self.x = x
939
940 def foo() -> None:
941 raise Failure(10)
942
943 def heyo() -> int:
944 try:
945 foo()
946 except Failure as e:
947 return e.x
948 return -1
949
950 [file driver.py]
951 from native import foo, heyo, Failure
952 try:
953 foo()
954 except Failure as e:
955 assert str(e) == '10'
956 assert e.x == 10
957 heyo()
958
959 [case testSubclassDict]
960 from typing import Dict
961 class WelpDict(Dict[str, int]):
962 def __init__(self) -> None:
963 self.emarhavil = 3
964 def foo(self) -> int:
965 return self.emarhavil
966
967 def welp() -> int:
968 x = WelpDict()
969 x['a'] = 10
970 x['b'] = 15
971 x.emarhavil = 5
972 return x['a'] + x['b'] + x.emarhavil + x.foo()
973
974 [file driver.py]
975 from native import welp
976 assert welp() == 35
977
978 [case testSubclassUnsupportedException]
979 from mypy_extensions import mypyc_attr
980
981 @mypyc_attr(native_class=False)
982 class MyError(ZeroDivisionError):
983 pass
984
985 @mypyc_attr(native_class=False)
986 class MyError2(ZeroDivisionError):
987 def __init__(self, s: str) -> None:
988 super().__init__(s + "!")
989 self.x = s.upper()
990
991 def f() -> None:
992 raise MyError("foobar")
993
994 def test_non_native_exception_subclass_basics() -> None:
995 e = MyError()
996 assert isinstance(e, MyError)
997 assert isinstance(e, ZeroDivisionError)
998 assert isinstance(e, Exception)
999
1000 e = MyError("x")
1001 assert repr(e) == "MyError('x')"
1002
1003 e2 = MyError2("ab")
1004 assert repr(e2) == "MyError2('ab!')", repr(e2)
1005 assert e2.x == "AB"
1006
1007 def test_raise_non_native_exception_subclass_1() -> None:
1008 try:
1009 f()
1010 except MyError:
1011 x = True
1012 else:
1013 assert False
1014 assert x
1015
1016 def test_raise_non_native_exception_subclass_2() -> None:
1017 try:
1018 f()
1019 except ZeroDivisionError:
1020 x = True
1021 else:
1022 assert False
1023 assert x
1024
1025 [case testSubclassPy]
1026 from b import B, V
1027 class A(B):
1028 def __init__(self, x: int, y: int) -> None:
1029 super().__init__(y)
1030 self.x = x
1031
1032 def foo(self, x: int) -> int:
1033 print("hi", x)
1034 return x+1
1035
1036 class C(V[int]):
1037 def f(self) -> int: return 10
1038
1039 assert isinstance(C(), V)
1040
1041 def f(x: A) -> None:
1042 print(x.x)
1043 print(x.y)
1044 print(x.foo(20))
1045
1046 [file b.py]
1047 from typing import Generic, TypeVar
1048 T = TypeVar('T')
1049
1050 class B:
1051 def __init__(self, y: int) -> None:
1052 self.y = y
1053 def foo(self, x: int) -> int:
1054 print("parent!")
1055 return x + self.y
1056 def bar(self) -> None:
1057 print("hello!", self.y)
1058
1059 class V(Generic[T]):
1060 def f(self) -> T:
1061 raise Exception('unimplemented')
1062 [file driver.py]
1063 import native
1064 a = native.A(10, 20)
1065 a.foo(10)
1066 a.bar()
1067 native.f(a)
1068 [out]
1069 hi 10
1070 hello! 20
1071 10
1072 20
1073 hi 20
1074 21
1075
1076 [case testDisallowSubclassFromPy]
1077 # We'll want to allow this at some point but right now we need to
1078 # disallow it because it doesn't work.
1079 class A:
1080 pass
1081 [file b.py]
1082 from native import A
1083
1084 # It would be better if we disallowed it at class decl time but it is
1085 # really easy to do in __new__
1086
1087 class B(A):
1088 pass
1089
1090 [file driver.py]
1091 from b import B
1092 try:
1093 B()
1094 except TypeError:
1095 pass
1096 else:
1097 assert False, "instantiating was supposed to fail"
1098
1099 [case testClassVariable]
1100 MYPY = False
1101 if MYPY:
1102 from typing import ClassVar
1103 class A:
1104 x = 10 # type: ClassVar[int]
1105
1106 def g(x: int) -> None:
1107 A.x = 10
1108 def f() -> int:
1109 return A.x
1110 [file driver.py]
1111 from native import A, f
1112 assert f() == 10
1113 A.x = 200
1114 assert f() == 200
1115
1116 [case testClassVarDoesNotShadowMethodGlobal]
1117 from typing import ClassVar
1118 from testutil import assertRaises
1119
1120 class E(Exception):
1121 pass
1122
1123 class C:
1124 E: ClassVar[type[E]] = E
1125
1126 def m(self, b: bytes) -> None:
1127 if not b:
1128 raise E()
1129
1130 def test_class_var_does_not_shadow_method_global() -> None:
1131 with assertRaises(E):
1132 C().m(b"")
1133
1134 [case testInitSubclassWithClassVar]
1135 from typing import ClassVar
1136
1137 class Base:
1138 name: ClassVar[str] = "base"
1139 required: ClassVar[int] = -1
1140
1141 def __init_subclass__(cls, **kwargs: object) -> None:
1142 cls.required = len(cls.name)
1143
1144 class Child(Base):
1145 name: ClassVar[str] = "child"
1146
1147 class GrandChild(Child):
1148 name: ClassVar[str] = "grandchild"
1149
1150 class NoOverride(Base):
1151 pass
1152
1153 [file driver.py]
1154 from native import Base, Child, GrandChild, NoOverride
1155
1156 # __init_subclass__ should see the subclass's own ClassVar values
1157 assert Child.name == "child"
1158 assert Child.required == 5, f"expected 5, got {Child.required}"
1159
1160 assert GrandChild.name == "grandchild"
1161 assert GrandChild.required == 10, f"expected 10, got {GrandChild.required}"
1162
1163 # No override should use inherited value
1164 assert NoOverride.name == "base"
1165 assert NoOverride.required == 4, f"expected 4, got {NoOverride.required}"
1166
1167 [case testDefaultVars]
1168 from typing import Optional
1169 class A:
1170 x = 10
1171 w: object = 10
1172 def lol(self) -> None:
1173 self.x = 100
1174
1175 LOL = 'lol'
1176 class B(A):
1177 y = LOL
1178 z = None # type: Optional[str]
1179 b = True
1180 bogus = None # type: int # type: ignore
1181
1182 def g() -> None:
1183 a = A()
1184 assert a.x == 10
1185 a.x = 20
1186 assert a.x == 20
1187 b = B()
1188 assert b.x == 10
1189 b.x = 20
1190 assert b.x == 20
1191 assert b.y == 'lol'
1192 b.y = 'rofl'
1193 assert b.y == 'rofl'
1194 assert b.z is None
1195 [file driver.py]
1196 from native import *
1197 g()
1198
1199 a = A()
1200 assert a.x == 10
1201 a.x = 20
1202 assert a.x == 20
1203 b = B()
1204 assert b.x == 10
1205 b.x = 20
1206 assert b.x == 20
1207 assert b.y == 'lol'
1208 b.y = 'rofl'
1209 assert b.y == 'rofl'
1210 assert b.z is None
1211 # N.B: this doesn't match cpython
1212 assert not hasattr(b, 'bogus')
1213
1214 [case testProtocol]
1215 from typing import Protocol
1216
1217 class Proto(Protocol):
1218 def foo(self, x: int) -> None:
1219 pass
1220
1221 def bar(self, x: int) -> None:
1222 pass
1223
1224 class A:
1225 def foo(self, x: int) -> None:
1226 print("A:", x)
1227
1228 def bar(self, *args: int, **kwargs: int) -> None:
1229 print("A:", args, kwargs)
1230
1231 class B(A, Proto):
1232 def foo(self, x: int) -> None:
1233 print("B:", x)
1234
1235 def bar(self, *args: int, **kwargs: int) -> None:
1236 print("B:", args, kwargs)
1237
1238 def f(x: Proto) -> None:
1239 x.foo(20)
1240 x.bar(x=20)
1241
1242 [file driver.py]
1243 from native import A, B, f
1244
1245 f(A())
1246 f(B())
1247
1248 # ... this exploits a bug in glue methods to distinguish whether we
1249 # are making a direct call or a pycall...
1250 [out]
1251 A: 20
1252 A: () {'x': 20}
1253 B: 20
1254 B: (20,) {}
1255
1256 [case testMethodOverrideDefault1]
1257 class A:
1258 def foo(self, x: int) -> None:
1259 pass
1260 class B(A):
1261 def foo(self, x: int, y: int = 10) -> None:
1262 print(x, y)
1263
1264 def a(x: A) -> None:
1265 x.foo(1)
1266 def b(x: B) -> None:
1267 x.foo(2)
1268 x.foo(2, 3)
1269
1270 [file driver.py]
1271 from native import B, a, b
1272 a(B())
1273 b(B())
1274 [out]
1275 1 10
1276 2 10
1277 2 3
1278
1279 [case testMethodOverrideDefault2]
1280 class A:
1281 def foo(self, *, x: int = -1) -> None:
1282 pass
1283 def bar(self, *, x: int = -1, y: int = -1) -> None:
1284 pass
1285 def baz(self, x: int = -1) -> None:
1286 pass
1287 class B(A):
1288 def foo(self, *, y: int = 0, x: int = 0) -> None:
1289 print(x, y)
1290 def bar(self, *, y: int = 0, x: int = 0) -> None:
1291 print(x, y)
1292 def baz(self, x: int = 0, *, y: int = 0) -> None:
1293 print(x, y)
1294
1295 def a(x: A) -> None:
1296 x.foo(x=1)
1297 x.bar(x=1, y=2)
1298 x.bar(x=2, y=1)
1299 x.baz()
1300 x.baz(1)
1301 x.baz(x=2)
1302
1303 [file driver.py]
1304 from native import B, a
1305 a(B())
1306 [out]
1307 1 0
1308 1 2
1309 2 1
1310 0 0
1311 1 0
1312 2 0
1313
1314 [case testMethodOverrideDefault3]
1315 class A:
1316 @classmethod
1317 def foo(cls, *, x: int = 0) -> None:
1318 pass
1319 @staticmethod
1320 def bar(*, x: int = 0) -> None:
1321 pass
1322 @staticmethod
1323 def baz() -> object:
1324 pass
1325 class B(A):
1326 @classmethod
1327 def foo(cls, *, y: int = 0, x: int = 0) -> None:
1328 print(x, y)
1329 print(cls.__name__) # type: ignore
1330 @staticmethod
1331 def bar(*, y: int = 0, x: int = 0) -> None:
1332 print(x, y)
1333 @staticmethod
1334 def baz() -> int:
1335 return 10
1336
1337 # This is just to make sure that this stuff works even when the
1338 # methods might be overridden.
1339 class C(B):
1340 @classmethod
1341 def foo(cls, *, y: int = 0, x: int = 0) -> None:
1342 pass
1343 @staticmethod
1344 def bar(*, y: int = 0, x: int = 0) -> None:
1345 pass
1346 @staticmethod
1347 def baz() -> int:
1348 return 10
1349
1350 def a(x: A) -> None:
1351 x.foo(x=1)
1352 x.bar(x=1)
1353 print(x.baz())
1354
1355 [file driver.py]
1356 from native import B, a
1357 a(B())
1358 [out]
1359 1 0
1360 B
1361 1 0
1362 10
1363
1364 [case testMethodOverrideDefault4]
1365 class Foo:
1366 def f(self, x: int=20, *, z: int=10) -> None:
1367 pass
1368
1369 class Bar(Foo):
1370 def f(self, *args: int, **kwargs: int) -> None:
1371 print("stuff", args, kwargs)
1372
1373 def test_override() -> None:
1374 z: Foo = Bar()
1375 z.f(1, z=50)
1376 z.f()
1377
1378 [out]
1379 stuff (1,) {'z': 50}
1380 stuff () {}
1381
1382 [case testMethodOverrideDefault5]
1383 from testutil import make_python_function
1384 from mypy_extensions import mypyc_attr
1385 from typing import TypeVar, Any
1386
1387 @mypyc_attr(allow_interpreted_subclasses=True)
1388 class Foo:
1389 def f(self, x: int=20, *, z: int=10) -> None:
1390 print("Foo", x, z)
1391
1392 @make_python_function
1393 def baz_f(self: Any, *args: int, **kwargs: int) -> None:
1394 print("Baz", args, kwargs)
1395
1396 def test_override() -> None:
1397 # Make an "interpreted" subtype of Foo
1398 type2: Any = type
1399 Bar = type2('Bar', (Foo,), {})
1400 Baz = type2('Baz', (Foo,), {'f': baz_f})
1401
1402 y: Foo = Bar()
1403 y.f(1, z=2)
1404 y.f()
1405
1406 z: Foo = Baz()
1407 z.f(1, z=2)
1408 z.f()
1409
1410 [out]
1411 Foo 1 2
1412 Foo 20 10
1413 Baz (1,) {'z': 2}
1414 Baz () {}
1415
1416 [case testMethodOverrideDefault6]
1417 from typing import Optional
1418
1419 class Foo:
1420 def f(self, x: int=20) -> None:
1421 pass
1422
1423 class Bar(Foo):
1424 def f(self, x: Optional[int]=None) -> None:
1425 print(x)
1426
1427 def test_override() -> None:
1428 z: Foo = Bar()
1429 z.f(1)
1430 z.f()
1431
1432 [out]
1433 1
1434 None
1435
1436 [case testMethodOverrideDefault7]
1437 from typing import TypeVar, Any
1438
1439 class Foo:
1440 def f(self, x: int, *args: int, **kwargs: int) -> None:
1441 print("Foo", x, args, kwargs)
1442
1443 class Bar(Foo):
1444 def f(self, *args: int, **kwargs: int) -> None:
1445 print("Bar", args, kwargs)
1446
1447 def test_override() -> None:
1448 z: Foo = Bar()
1449 z.f(1, z=2)
1450 z.f(1, 2, 3)
1451 # z.f(x=5) # Not tested because we (knowingly) do the wrong thing and pass it as positional
1452
1453 [out]
1454 Bar (1,) {'z': 2}
1455 Bar (1, 2, 3) {}
1456 --Bar () {'x': 5}
1457
1458 [case testMethodOverrideDefault8]
1459 from typing import TypeVar, Any
1460
1461 class Foo:
1462 def f(self, *args: int, **kwargs: int) -> None:
1463 print("Foo", args, kwargs)
1464
1465 class Bar(Foo):
1466 def f(self, x: int = 10, *args: int, **kwargs: int) -> None:
1467 print("Bar", x, args, kwargs)
1468
1469 def test_override() -> None:
1470 z: Foo = Bar()
1471 z.f(1, z=2)
1472 z.f(1, 2, 3)
1473 z.f()
1474
1475 [out]
1476 Bar 1 () {'z': 2}
1477 Bar 1 (2, 3) {}
1478 Bar 10 () {}
1479
1480 [case testMethodOverrideDefault9]
1481 from testutil import make_python_function
1482 from mypy_extensions import mypyc_attr
1483 from typing import TypeVar, Any
1484
1485 @mypyc_attr(allow_interpreted_subclasses=True)
1486 class Foo:
1487 def f(self, x: int=20, y: int=40) -> None:
1488 print("Foo", x, y)
1489
1490 # This sort of argument renaming is dodgy and not really sound but we
1491 # shouldn't break it when they aren't actually used by name...
1492 # (They *ought* to be positional only!)
1493 @make_python_function
1494 def baz_f(self, a: int=30, y: int=50) -> None:
1495 print("Baz", a, y)
1496
1497 def test_override() -> None:
1498 # Make an "interpreted" subtype of Foo
1499 type2: Any = type
1500 Baz = type2('Baz', (Foo,), {'f': baz_f})
1501
1502 z: Foo = Baz()
1503 z.f()
1504 z.f(y=1)
1505 z.f(1, 2)
1506 # Not tested because we don't (and probably won't) match cpython here
1507 # from testutil import assertRaises
1508 # with assertRaises(TypeError):
1509 # z.f(x=7)
1510
1511 [out]
1512 Baz 30 50
1513 Baz 30 1
1514 Baz 1 2
1515
1516 [case testOverride]
1517 class A:
1518 def f(self) -> int:
1519 return 0
1520 def g(self) -> int:
1521 return 1
1522
1523 class B(A):
1524 def g(self) -> int:
1525 return 2
1526
1527 class C(B):
1528 def f(self) -> int:
1529 return 3
1530
1531 def test() -> None:
1532 ba: A = B()
1533 ca: A = C()
1534 assert ba.f() == 0
1535 assert ba.g() == 2
1536 assert ca.f() == 3
1537 assert ca.g() == 2
1538 cc = C()
1539 assert cc.f() == 3
1540 assert cc.g() == 2
1541 print('ok')
1542 [file driver.py]
1543 import native
1544 native.test()
1545 [out]
1546 ok
1547
1548 [case testNoMetaclass]
1549 from foo import Base
1550
1551 class Nothing(Base): # type: ignore
1552 pass
1553
1554 [file foo.py]
1555 from typing import Any
1556 class Meta(type):
1557 pass
1558
1559 class _Base(metaclass=Meta):
1560 pass
1561 Base = _Base # type: Any
1562
1563 [file driver.py]
1564 try:
1565 import native
1566 except TypeError as e:
1567 assert(str(e) == "mypyc classes can't have a metaclass")
1568
1569 [case testMetaclass]
1570 from meta import Meta
1571
1572 class Nothing(metaclass=Meta):
1573 pass
1574
1575 def ident(x): return x
1576
1577 @ident
1578 class Test:
1579 pass
1580
1581 [file meta.py]
1582 class Meta(type):
1583 def __new__(mcs, name, bases, dct):
1584 dct['X'] = 10
1585 return super().__new__(mcs, name, bases, dct)
1586
1587
1588 [file driver.py]
1589 from native import Nothing
1590 assert Nothing.X == 10
1591
1592 [case testPickling]
1593 from mypy_extensions import trait, mypyc_attr
1594 from typing import Any, TypeVar, Generic
1595
1596 def dec(x: Any) -> Any:
1597 return x
1598
1599 @mypyc_attr(allow_interpreted_subclasses=True)
1600 class A:
1601 x: int
1602 y: str
1603
1604 @mypyc_attr(allow_interpreted_subclasses=True)
1605 class B(A):
1606 z: bool
1607
1608 def __init__(self, x: int, y: str, z: bool) -> None:
1609 self.x = x
1610 self.y = y
1611 self.z = z
1612
1613 @trait
1614 class T:
1615 a: str
1616
1617 class C(B, T):
1618 w: object
1619
1620 # property shouldn't go in
1621 @property
1622 def foo(self) -> int:
1623 return 0
1624
1625 @dec
1626 class D:
1627 x: int
1628
1629 class E(D):
1630 y: int
1631
1632
1633 U = TypeVar('U')
1634
1635 class F(Generic[U]):
1636 y: int
1637
1638 class G(F[int]):
1639 pass
1640
1641 [file driver.py]
1642 from native import A, B, T, C, D, E, F, G
1643
1644 import copy
1645 import pickle
1646
1647 assert A.__mypyc_attrs__ == ('x', 'y')
1648 assert B.__mypyc_attrs__ == ('z', 'x', 'y')
1649 assert T.__mypyc_attrs__ == ('a',)
1650 assert C.__mypyc_attrs__ == ('w', 'z', 'x', 'y', 'a')
1651 assert not hasattr(D, '__mypyc_attrs__')
1652 assert E.__mypyc_attrs__ == ('y', '__dict__')
1653 assert F.__mypyc_attrs__ == ('y', '__dict__')
1654 assert G.__mypyc_attrs__ == ('y', '__dict__')
1655
1656 b = B(10, '20', False)
1657 assert b.__getstate__() == {'z': False, 'x': 10, 'y': '20'}
1658 b2 = copy.copy(b)
1659 assert b is not b2 and b.y == b2.y
1660
1661 b3 = pickle.loads(pickle.dumps(b))
1662 assert b is not b3 and b.y == b3.y
1663
1664 e = E()
1665 e.x = 10
1666 e.y = 20
1667
1668 assert e.__getstate__() == {'y': 20, '__dict__': {'x': 10}}
1669 e2 = pickle.loads(pickle.dumps(e))
1670 assert e is not e2 and e.x == e2.x and e.y == e2.y
1671
1672
1673 [case testInterpretedParentInit]
1674 from interp import C
1675 from typing import TypeVar
1676
1677 T = TypeVar('T')
1678
1679 def dec(x: T) -> T:
1680 return x
1681
1682 @dec
1683 class A:
1684 def __init__(self, x: int) -> None:
1685 self.x = x
1686
1687 class B(A):
1688 s = 'test'
1689
1690 def b(x: int) -> B: return B(x)
1691
1692 class D(C):
1693 s = 'test'
1694
1695 def d(x: int) -> D: return D(x)
1696
1697
1698 [file interp.py]
1699 class C:
1700 def __init__(self, x: int) -> None:
1701 self.x = x
1702
1703 [file driver.py]
1704 from native import b, d, B, D
1705
1706 def test(f, v):
1707 x = f(v)
1708 assert x.x == v
1709 assert x.s == 'test'
1710
1711 test(b, 20)
1712 test(d, 30)
1713 test(B, -1)
1714 test(D, -2)
1715
1716 [case testInterpretedInherit]
1717 from typing import TypeVar, Any, overload
1718 from mypy_extensions import mypyc_attr, trait
1719
1720 T = TypeVar('T')
1721 def dec(x: T) -> T: return x
1722
1723 @mypyc_attr(allow_interpreted_subclasses=True)
1724 class Top:
1725 def spam(self) -> str:
1726 return "grandparent"
1727
1728 @mypyc_attr(allow_interpreted_subclasses=True)
1729 @trait
1730 class Trait:
1731 def trait_method(self) -> str:
1732 return "trait"
1733
1734 @mypyc_attr(allow_interpreted_subclasses=True)
1735 class Foo(Top, Trait):
1736 def __init__(self, x: int) -> None:
1737 self.x = x
1738
1739 def foo(self) -> str:
1740 return "parent foo: " + self.bar(self.x)
1741
1742 def bar(self, x: int) -> str:
1743 return "parent bar: {}".format(x + self.x)
1744
1745 @dec
1746 def decorated(self) -> str:
1747 return "decorated parent"
1748
1749 @property
1750 def read_property(self) -> str:
1751 return "parent prop"
1752
1753 @overload
1754 def overloaded(self, index: int) -> int: ...
1755
1756 @overload
1757 def overloaded(self, index: str) -> str: ...
1758
1759 def overloaded(self, index: Any) -> Any:
1760 return index
1761
1762 def foo(x: Foo) -> str:
1763 return x.foo()
1764
1765 def bar(x: Foo, y: int) -> str:
1766 return x.bar(y)
1767
1768 def spam(x: Top) -> str:
1769 return x.spam()
1770
1771 def decorated(x: Foo) -> str:
1772 return x.decorated()
1773
1774 def prop(x: Foo) -> str:
1775 return x.read_property
1776
1777 def trait_method(x: Trait) -> str:
1778 return x.trait_method()
1779
1780 def overloaded(x: Foo, s: str) -> str:
1781 return x.overloaded(s)
1782
1783 [file interp.py]
1784 from typing import Any
1785 from native import Foo
1786
1787 class Bar(Foo):
1788 def bar(self, x: int) -> str:
1789 return "child bar: {}".format(x + self.x)
1790
1791 def spam(self) -> str:
1792 assert super().spam() == "grandparent"
1793 return "child"
1794
1795 @property
1796 def read_property(self) -> str:
1797 return "child prop"
1798
1799 def decorated(self) -> str:
1800 return "decorated child"
1801
1802 def trait_method(self) -> str:
1803 return "child"
1804
1805 def overloaded(self, index: Any) -> Any:
1806 return index + index
1807
1808
1809 class InterpBase:
1810 def eggs(self) -> str:
1811 return "eggs"
1812
1813 class Baz(InterpBase, Bar):
1814 def __init__(self) -> None:
1815 super().__init__(1000)
1816 self.z = self.read_property
1817
1818 [file driver.py]
1819 from native import Foo, foo, bar, spam, decorated, overloaded, prop, trait_method
1820 from interp import Bar, Baz
1821 from unittest.mock import patch
1822 from testutil import assertRaises
1823
1824 x = Foo(10)
1825 y = Bar(20)
1826 z = Baz()
1827
1828 assert isinstance(y, Bar)
1829 assert y.x == 20
1830 assert y.bar(10) == "child bar: 30"
1831 assert y.foo() == "parent foo: child bar: 40"
1832 assert foo(y) == "parent foo: child bar: 40"
1833 assert bar(y, 30) == "child bar: 50"
1834 y.x = 30
1835 assert bar(y, 30) == "child bar: 60"
1836
1837 assert spam(y) == "child"
1838 assert y.read_property == "child prop"
1839 assert prop(x) == "parent prop"
1840 assert prop(y) == "child prop"
1841 assert y.decorated() == "decorated child"
1842 assert decorated(y) == "decorated child"
1843 assert y.overloaded("test") == "testtest"
1844 assert overloaded(y, "test") == "testtest"
1845
1846 assert y.trait_method() == "child"
1847 assert trait_method(y) == "child"
1848
1849 assert z.bar(10) == "child bar: 1010"
1850 assert bar(z, 10) == "child bar: 1010"
1851 assert z.z == "child prop"
1852 assert z.eggs() == "eggs"
1853
1854 with patch("interp.Bar.spam", lambda self: "monkey patched"):
1855 assert y.spam() == "monkey patched"
1856 spam(y) == "monkey patched"
1857
1858 with patch("interp.Bar.spam", lambda self: 20):
1859 assert y.spam() == 20
1860 with assertRaises(TypeError, "str object expected; got int"):
1861 spam(y)
1862
1863 with assertRaises(TypeError, "int object expected; got str"):
1864 y.x = "test"
1865
1866 [case testProperty]
1867 from typing import Callable
1868 from mypy_extensions import trait
1869 class Temperature:
1870 @property
1871 def celsius(self) -> float:
1872 return 5.0 * (self.fahrenheit - 32.0) / 9.0
1873
1874 def __init__(self, fahrenheit: float) -> None:
1875 self.fahrenheit = fahrenheit
1876
1877 def print_temp(self) -> None:
1878 print("F:", self.fahrenheit, "C:", self.celsius)
1879
1880 @property
1881 def rankine(self) -> float:
1882 raise NotImplementedError
1883
1884 class Access:
1885 @property
1886 def number_of_accesses(self) -> int:
1887 self._count += 1
1888 return self._count
1889 def __init__(self) -> None:
1890 self._count = 0
1891
1892 from typing import Callable
1893 class BaseProperty:
1894 @property
1895 def doc(self) -> str:
1896 return "Represents a sequence of values. Updates itself by next, which is a new value."
1897
1898 @property
1899 def value(self) -> object:
1900 return self._incrementer
1901
1902 @property
1903 def bad_value(self) -> object:
1904 return self._incrementer
1905
1906 @property
1907 def next(self) -> BaseProperty:
1908 return BaseProperty(self._incrementer + 1)
1909
1910 def __init__(self, value: int) -> None:
1911 self._incrementer = value
1912
1913 class DerivedProperty(BaseProperty):
1914 @property
1915 def value(self) -> int:
1916 return self._incrementer
1917
1918 @property
1919 def bad_value(self) -> object:
1920 return self._incrementer
1921
1922 def __init__(self, incr_func: Callable[[int], int], value: int) -> None:
1923 BaseProperty.__init__(self, value)
1924 self._incr_func = incr_func
1925
1926 @property
1927 def next(self) -> DerivedProperty:
1928 return DerivedProperty(self._incr_func, self._incr_func(self.value))
1929
1930 class AgainProperty(DerivedProperty):
1931 @property
1932 def next(self) -> AgainProperty:
1933 return AgainProperty(self._incr_func, self._incr_func(self._incr_func(self.value)))
1934
1935 @property
1936 def bad_value(self) -> int:
1937 return self._incrementer
1938
1939 def print_first_n(n: int, thing: BaseProperty) -> None:
1940 vals = []
1941 cur_thing = thing
1942 for _ in range(n):
1943 vals.append(cur_thing.value)
1944 cur_thing = cur_thing.next
1945 print ('', vals)
1946
1947 @trait
1948 class Trait:
1949 @property
1950 def value(self) -> int:
1951 return 3
1952
1953 class Printer(Trait):
1954 def print_value(self) -> None:
1955 print(self.value)
1956
1957 [file driver.py]
1958 from native import Temperature, Access
1959 import traceback
1960 x = Temperature(32.0)
1961 try:
1962 print (x.rankine)
1963 except NotImplementedError as e:
1964 traceback.print_exc()
1965 print (x.celsius)
1966 x.print_temp()
1967
1968 y = Temperature(212.0)
1969 print (y.celsius)
1970 y.print_temp()
1971
1972 z = Access()
1973 print (z.number_of_accesses)
1974 print (z.number_of_accesses)
1975 print (z.number_of_accesses)
1976 print (z.number_of_accesses)
1977
1978 from native import BaseProperty, DerivedProperty, AgainProperty, print_first_n
1979 a = BaseProperty(7)
1980 b = DerivedProperty((lambda x: x // 2 if (x % 2 == 0) else 3 * x + 1), 7)
1981 c = AgainProperty((lambda x: x // 2 if (x % 2 == 0) else 3 * x + 1), 7)
1982
1983 def py_print_first_n(n: int, thing: BaseProperty) -> None:
1984 vals = []
1985 cur_thing = thing
1986 for _ in range(n):
1987 vals.append(cur_thing.value)
1988 cur_thing = cur_thing.next
1989 print ('', vals)
1990
1991 py_print_first_n(20, a)
1992 py_print_first_n(20, b)
1993 py_print_first_n(20, c)
1994
1995 print(a.next.next.next.bad_value)
1996 print(b.next.next.next.bad_value)
1997 print(c.next.next.next.bad_value)
1998
1999 print_first_n(20, a)
2000 print_first_n(20, b)
2001 print_first_n(20, c)
2002
2003 print (a.doc)
2004 print (b.doc)
2005 print (c.doc)
2006
2007 from native import Printer
2008 Printer().print_value()
2009 print (Printer().value)
2010 [out]
2011 Traceback (most recent call last):
2012 File "driver.py", line 5, in <module>
2013 print (x.rankine)
2014 File "native.py", line 16, in rankine
2015 raise NotImplementedError
2016 NotImplementedError
2017 0.0
2018 F: 32.0 C: 0.0
2019 100.0
2020 F: 212.0 C: 100.0
2021 1
2022 2
2023 3
2024 4
2025 [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
2026 [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
2027 [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
2028 10
2029 34
2030 26
2031 [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
2032 [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
2033 [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
2034 Represents a sequence of values. Updates itself by next, which is a new value.
2035 Represents a sequence of values. Updates itself by next, which is a new value.
2036 Represents a sequence of values. Updates itself by next, which is a new value.
2037 3
2038 3
2039 [out version>=3.11]
2040 Traceback (most recent call last):
2041 File "driver.py", line 5, in <module>
2042 print (x.rankine)
2043 ^^^^^^^^^
2044 File "native.py", line 16, in rankine
2045 raise NotImplementedError
2046 NotImplementedError
2047 0.0
2048 F: 32.0 C: 0.0
2049 100.0
2050 F: 212.0 C: 100.0
2051 1
2052 2
2053 3
2054 4
2055 [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
2056 [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
2057 [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
2058 10
2059 34
2060 26
2061 [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
2062 [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]
2063 [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]
2064 Represents a sequence of values. Updates itself by next, which is a new value.
2065 Represents a sequence of values. Updates itself by next, which is a new value.
2066 Represents a sequence of values. Updates itself by next, which is a new value.
2067 3
2068 3
2069
2070 [case testPropertySetters]
2071
2072 from mypy_extensions import trait
2073
2074 class Foo():
2075 def __init__(self) -> None:
2076 self.attr = "unmodified"
2077
2078 class A:
2079 def __init__(self) -> None:
2080 self._x = 0
2081 self._foo = Foo()
2082
2083 @property
2084 def x(self) -> int:
2085 return self._x
2086
2087 @x.setter
2088 def x(self, val : int) -> None:
2089 self._x = val
2090
2091 @property
2092 def foo(self) -> Foo:
2093 return self._foo
2094
2095 @foo.setter
2096 def foo(self, val : Foo) -> None:
2097 self._foo = val
2098
2099 # Overrides base property setters and getters
2100 class B(A):
2101 def __init__(self) -> None:
2102 self._x = 10
2103
2104 @property
2105 def x(self) -> int:
2106 return self._x + 1
2107
2108 @x.setter
2109 def x(self, val : int) -> None:
2110 self._x = val + 1
2111
2112 # Inherits base property setters and getters
2113 class C(A):
2114 def __init__(self) -> None:
2115 A.__init__(self)
2116
2117 @trait
2118 class D():
2119 def __init__(self) -> None:
2120 self._x = 0
2121
2122 @property
2123 def x(self) -> int:
2124 return self._x
2125
2126 @x.setter
2127 def x(self, val : int) -> None:
2128 self._x = val
2129
2130 #Inherits trait property setters and getters
2131 class E(D):
2132 def __init__(self) -> None:
2133 D.__init__(self)
2134
2135 #Overrides trait property setters and getters
2136 class F(D):
2137 def __init__(self) -> None:
2138 self._x = 10
2139
2140 @property
2141 def x(self) -> int:
2142 return self._x + 10
2143
2144 @x.setter
2145 def x(self, val : int) -> None:
2146 self._x = val + 10
2147
2148 # # Property setter and getter are subtypes of base property setters and getters
2149 # # class G(A):
2150 # # def __init__(self) -> None:
2151 # # A.__init__(self)
2152
2153 # # @property
2154 # # def y(self) -> int:
2155 # # return self._y
2156
2157 # # @y.setter
2158 # # def y(self, val : object) -> None:
2159 # # self._y = val
2160
2161 # No inheritance, just plain setter/getter
2162 class G:
2163 def __init__(self, x: int) -> None:
2164 self._x = x
2165
2166 @property
2167 def x(self) -> int:
2168 return self._x
2169
2170 @x.setter
2171 def x(self, x: int) -> None:
2172 self._x = x
2173
2174 class H:
2175 def __init__(self, g: G) -> None:
2176 self.g = g
2177 self.g.x = 5 # Should not be treated as initialization
2178
2179 [file other.py]
2180 # Run in both interpreted and compiled mode
2181 import gc
2182
2183 from native import A, B, C, D, E, F, Foo, G
2184
2185 def test_leaks() -> None:
2186 a = A()
2187
2188 gc.collect()
2189 before = gc.get_objects()
2190 for _ in range(100):
2191 a.foo = Foo()
2192 gc.collect()
2193 after = gc.get_objects()
2194
2195 diff = len(after) - len(before)
2196 # Small difference is expected, if the property setter call was leaking objects
2197 # we would get a difference similar to the number of iterations above.
2198 assert diff <= 2, diff
2199
2200 def set_foo(foo: Foo) -> None:
2201 a = A()
2202 a.foo = foo
2203
2204 def test_use_after_passing_to_prop_setter() -> None:
2205 foo = Foo()
2206
2207 foo.attr = "before"
2208 assert foo.attr == "before", foo.attr
2209
2210 set_foo(foo)
2211 assert foo.attr == "before", foo.attr
2212
2213 foo.attr = "after"
2214 assert foo.attr == "after", foo.attr
2215
2216 a = A()
2217 assert a.x == 0
2218 assert a._x == 0
2219 a.x = 1
2220 assert a.x == 1
2221 assert a._x == 1
2222 a._x = 0
2223 assert a.x == 0
2224 assert a._x == 0
2225 b = B()
2226 assert b.x == 11
2227 assert b._x == 10
2228 b.x = 11
2229 assert b.x == 13
2230 b._x = 11
2231 assert b.x == 12
2232 c = C()
2233 assert c.x == 0
2234 c.x = 1000
2235 assert c.x == 1000
2236 e = E()
2237 assert e.x == 0
2238 e.x = 1000
2239 assert e.x == 1000
2240 f = F()
2241 assert f.x == 20
2242 f.x = 30
2243 assert f.x == 50
2244 g = G(4)
2245 g.x = 20
2246 assert g.x == 20
2247
2248 test_leaks()
2249 test_use_after_passing_to_prop_setter()
2250
2251 [file driver.py]
2252 # Run the tests in both interpreted and compiled mode
2253 import other
2254 import other_interpreted
2255
2256 [out]
2257
2258 [case testAttributeOverridesProperty]
2259 from typing import Any
2260 from mypy_extensions import trait
2261
2262 @trait
2263 class T1:
2264 @property
2265 def x(self) -> int: ...
2266 @property
2267 def y(self) -> int: ...
2268
2269 class C1(T1):
2270 x: int = 1
2271 y: int = 4
2272
2273 def test_read_only_property_in_trait_implemented_as_attribute() -> None:
2274 c = C1()
2275 c.x = 5
2276 assert c.x == 5
2277 assert c.y == 4
2278 c.y = 6
2279 assert c.y == 6
2280 t: T1 = C1()
2281 assert t.y == 4
2282 t = c
2283 assert t.x == 5
2284 assert t.y == 6
2285 a: Any = c
2286 assert a.x == 5
2287 assert a.y == 6
2288 a.x = 7
2289 a.y = 8
2290 assert a.x == 7
2291 assert a.y == 8
2292
2293 class B2:
2294 @property
2295 def x(self) -> int:
2296 return 11
2297
2298 @property
2299 def y(self) -> int:
2300 return 25
2301
2302 class C2(B2):
2303 x: int = 1
2304 y: int = 4
2305
2306 def test_read_only_property_in_class_implemented_as_attribute() -> None:
2307 c = C2()
2308 c.x = 5
2309 assert c.x == 5
2310 assert c.y == 4
2311 c.y = 6
2312 assert c.y == 6
2313 b: B2 = C2()
2314 assert b.y == 4
2315 b = c
2316 assert b.x == 5
2317 assert b.y == 6
2318 a: Any = c
2319 assert a.x == 5
2320 assert a.y == 6
2321 a.x = 7
2322 a.y = 8
2323 assert a.x == 7
2324 assert a.y == 8
2325
2326 @trait
2327 class T3:
2328 @property
2329 def x(self) -> int: ...
2330 @property
2331 def y(self) -> int: ...
2332
2333 class B3:
2334 x: int = 1
2335 y: int = 4
2336
2337 class C3(B3, T3):
2338 pass
2339
2340 def test_read_only_property_implemented_as_attribute_indirectly() -> None:
2341 c = C3()
2342 c.x = 5
2343 assert c.x == 5
2344 assert c.y == 4
2345 c.y = 6
2346 assert c.y == 6
2347 t: T3 = C3()
2348 assert t.y == 4
2349 t = c
2350 assert t.x == 5
2351 assert t.y == 6
2352 a: Any = c
2353 assert a.x == 5
2354 assert a.y == 6
2355 a.x = 7
2356 a.y = 8
2357 assert a.x == 7
2358 assert a.y == 8
2359
2360 @trait
2361 class T4:
2362 @property
2363 def x(self) -> int: ...
2364 @x.setter
2365 def x(self, v1: int) -> None: ...
2366
2367 @property
2368 def y(self) -> int: ...
2369 @y.setter
2370 def y(self, v2: int) -> None: ...
2371
2372 class C4(T4):
2373 x: int = 1
2374 y: int = 4
2375
2376 def test_read_write_property_implemented_as_attribute() -> None:
2377 c = C4()
2378 c.x = 5
2379 assert c.x == 5
2380 assert c.y == 4
2381 c.y = 6
2382 assert c.y == 6
2383 t: T4 = C4()
2384 assert t.y == 4
2385 t.x = 5
2386 assert t.x == 5
2387 t.y = 6
2388 assert t.y == 6
2389 a: Any = c
2390 assert a.x == 5
2391 assert a.y == 6
2392 a.x = 7
2393 a.y = 8
2394 assert a.x == 7
2395 assert a.y == 8
2396
2397 @trait
2398 class T5:
2399 @property
2400 def x(self) -> int: ...
2401 @x.setter
2402 def x(self, v1: int) -> None: ...
2403
2404 @property
2405 def y(self) -> int: ...
2406 @y.setter
2407 def y(self, v2: int) -> None: ...
2408
2409 class B5:
2410 x: int = 1
2411 y: int = 4
2412
2413 class BB5(B5):
2414 pass
2415
2416 class C5(BB5, T5):
2417 pass
2418
2419 def test_read_write_property_indirectly_implemented_as_attribute() -> None:
2420 c = C5()
2421 c.x = 5
2422 assert c.x == 5
2423 assert c.y == 4
2424 c.y = 6
2425 assert c.y == 6
2426 t: T5 = C5()
2427 assert t.y == 4
2428 t.x = 5
2429 assert t.x == 5
2430 t.y = 6
2431 assert t.y == 6
2432 a: Any = c
2433 assert a.x == 5
2434 assert a.y == 6
2435 a.x = 7
2436 a.y = 8
2437 assert a.x == 7
2438 assert a.y == 8
2439
2440 [case testSubclassAttributeAccess]
2441 from mypy_extensions import trait
2442
2443 class A:
2444 v = 0
2445
2446 class B(A):
2447 v = 1
2448
2449 class C(B):
2450 v = 2
2451
2452 [file driver.py]
2453 from native import A, B, C
2454
2455 a = A()
2456 b = B()
2457 c = C()
2458
2459 [case testCopyAlwaysDefinedAttributes]
2460 import copy
2461 from typing import Union
2462
2463 class A: pass
2464
2465 class C:
2466 def __init__(self, n: int = 0) -> None:
2467 self.n = n
2468 self.s = ""
2469 self.t = ("", 0)
2470 self.u: Union[str, bytes] = ''
2471 self.a = A()
2472
2473 def test_copy() -> None:
2474 c1 = C()
2475 c1.n = 1
2476 c1.s = "x"
2477 c2 = copy.copy(c1)
2478 assert c2.n == 1
2479 assert c2.s == "x"
2480 assert c2.t == ("", 0)
2481 assert c2.u == ''
2482 assert c2.a is c1.a
2483
2484 [case testNonNativeCallsToDunderNewAndInit]
2485 from typing import Any
2486 from testutil import assertRaises
2487
2488 count_c = 0
2489
2490 class C:
2491 def __init__(self) -> None:
2492 self.x = 'a' # Always defined attribute
2493 global count_c
2494 count_c += 1
2495
2496 def get(self) -> str:
2497 return self.x
2498
2499 def test_no_init_args() -> None:
2500 global count_c
2501 count_c = 0
2502
2503 # Use Any to get non-native semantics
2504 cls: Any = C
2505 # __new__ implicitly calls __init__ for native classes
2506 obj = cls.__new__(cls)
2507 assert obj.get() == 'a'
2508 assert count_c == 1
2509 # Make sure we don't call __init__ twice
2510 obj2 = cls()
2511 assert obj2.get() == 'a'
2512 assert count_c == 2
2513
2514 count_d = 0
2515
2516 class D:
2517 def __init__(self, x: str) -> None:
2518 self.x = x # Always defined attribute
2519 global count_d
2520 count_d += 1
2521
2522 def get(self) -> str:
2523 return self.x
2524
2525 def test_init_arg() -> None:
2526 global count_d
2527 count_d = 0
2528
2529 # Use Any to get non-native semantics
2530 cls: Any = D
2531 # __new__ implicitly calls __init__ for native classes
2532 obj = cls.__new__(cls, 'abc')
2533 assert obj.get() == 'abc'
2534 assert count_d == 1
2535 # Make sure we don't call __init__ twice
2536 obj2 = cls('x')
2537 assert obj2.get() == 'x'
2538 assert count_d == 2
2539 # Keyword args should work
2540 obj = cls.__new__(cls, x='abc')
2541 assert obj.get() == 'abc'
2542 assert count_d == 3
2543
2544 def test_invalid_init_args() -> None:
2545 # Use Any to get non-native semantics
2546 cls: Any = D
2547 with assertRaises(TypeError):
2548 cls()
2549 with assertRaises(TypeError):
2550 cls(y='x')
2551 with assertRaises(TypeError):
2552 cls(1)
2553
2554 [case testTryDeletingAlwaysDefinedAttribute]
2555 from typing import Any
2556 from testutil import assertRaises
2557
2558 class C:
2559 def __init__(self) -> None:
2560 self.x = 0
2561
2562 class D(C):
2563 pass
2564
2565 def test_try_deleting_always_defined_attr() -> None:
2566 c: Any = C()
2567 with assertRaises(AttributeError):
2568 del c.x
2569 d: Any = D()
2570 with assertRaises(AttributeError):
2571 del d.x
2572
2573 [case testAlwaysDefinedAttributeAndAllowInterpretedSubclasses]
2574 from mypy_extensions import mypyc_attr
2575
2576 from m import define_interpreted_subclass
2577
2578 @mypyc_attr(allow_interpreted_subclasses=True)
2579 class Base:
2580 x = 5
2581 y: int
2582 def __init__(self, s: str) -> None:
2583 self.s = s
2584
2585 class DerivedNative(Base):
2586 def __init__(self) -> None:
2587 super().__init__('x')
2588 self.z = 3
2589
2590 def test_native_subclass() -> None:
2591 o = DerivedNative()
2592 assert o.x == 5
2593 assert o.s == 'x'
2594 assert o.z == 3
2595
2596 def test_interpreted_subclass() -> None:
2597 define_interpreted_subclass(Base)
2598
2599 [file m.py]
2600 from testutil import assertRaises
2601
2602 def define_interpreted_subclass(b):
2603 class DerivedInterpreted1(b): # type: ignore[misc, valid-type]
2604 def __init__(self):
2605 # Don't call base class __init__
2606 pass
2607 d1 = DerivedInterpreted1()
2608 assert d1.x == 5
2609 with assertRaises(AttributeError):
2610 d1.y
2611 with assertRaises(AttributeError):
2612 d1.s
2613 with assertRaises(AttributeError):
2614 del d1.x
2615
2616 class DerivedInterpreted2(b): # type: ignore[misc, valid-type]
2617 def __init__(self):
2618 super().__init__('y')
2619 d2 = DerivedInterpreted2()
2620 assert d2.x == 5
2621 assert d2.s == 'y'
2622 with assertRaises(AttributeError):
2623 d2.y
2624 with assertRaises(AttributeError):
2625 del d2.x
2626
2627 [case testBaseClassSometimesDefinesAttribute]
2628 class C:
2629 def __init__(self, b: bool) -> None:
2630 if b:
2631 self.x = [1]
2632
2633 class D(C):
2634 def __init__(self, b: bool) -> None:
2635 super().__init__(b)
2636 self.x = [2]
2637
2638 def test_base_class() -> None:
2639 c = C(True)
2640 assert c.x == [1]
2641 c = C(False)
2642 try:
2643 c.x
2644 except AttributeError:
2645 return
2646 assert False
2647
2648 def test_subclass() -> None:
2649 d = D(True)
2650 assert d.x == [2]
2651 d = D(False)
2652 assert d.x == [2]
2653
2654 [case testSerializableClass]
2655 from mypy_extensions import mypyc_attr
2656 from typing import Any
2657 import copy
2658 from testutil import assertRaises
2659
2660 @mypyc_attr(serializable=True)
2661 class Base:
2662 def __init__(self, s: str) -> None:
2663 self.s = s
2664
2665 class Derived(Base):
2666 def __init__(self, s: str, n: int) -> None:
2667 super().__init__(s)
2668 self.n = n
2669
2670 def test_copy_base() -> None:
2671 o = Base('xyz')
2672 o2 = copy.copy(o)
2673 assert isinstance(o2, Base)
2674 assert o2 is not o
2675 assert o2.s == 'xyz'
2676
2677 def test_copy_derived() -> None:
2678 d = Derived('xyz', 5)
2679 d2 = copy.copy(d)
2680 assert isinstance(d2, Derived)
2681 assert d2 is not d
2682 assert d2.s == 'xyz'
2683 assert d2.n == 5
2684
2685 class NonSerializable:
2686 def __init__(self, s: str) -> None:
2687 self.s = s
2688
2689 @mypyc_attr(serializable=True)
2690 class SerializableSub(NonSerializable):
2691 def __init__(self, s: str, n: int) -> None:
2692 super().__init__(s)
2693 self.n = n
2694
2695 def test_serializable_sub_class() -> None:
2696 n = NonSerializable('xyz')
2697 assert n.s == 'xyz'
2698
2699 with assertRaises(TypeError):
2700 copy.copy(n)
2701
2702 s = SerializableSub('foo', 6)
2703 s2 = copy.copy(s)
2704 assert s2 is not s
2705 assert s2.s == 'foo'
2706 assert s2.n == 6
2707
2708 def test_serializable_sub_class_call_new() -> None:
2709 t: Any = SerializableSub
2710 sub: SerializableSub = t.__new__(t)
2711 with assertRaises(AttributeError):
2712 sub.s
2713 with assertRaises(AttributeError):
2714 sub.n
2715 base: NonSerializable = sub
2716 with assertRaises(AttributeError):
2717 base.s
2718
2719 [case testClassWithInherited__call__]
2720 class Base:
2721 def __call__(self) -> int:
2722 return 1
2723
2724 class Derived(Base):
2725 pass
2726
2727 def test_inherited() -> None:
2728 assert Derived()() == 1
2729
2730 [case testClassWithFinalAttribute]
2731 from typing import Final
2732
2733 class C:
2734 A: Final = -1
2735 a: Final = [A]
2736
2737 def test_final_attribute() -> None:
2738 assert C.A == -1
2739 assert C.a == [-1]
2740
2741 [case testClassWithFinalDecorator]
2742 from typing import final
2743
2744 @final
2745 class C:
2746 def a(self) -> int:
2747 return 1
2748
2749 def test_class_final_attribute() -> None:
2750 assert C().a() == 1
2751
2752
2753 [case testClassWithFinalDecoratorCtor]
2754 from typing import final
2755
2756 @final
2757 class C:
2758 def __init__(self) -> None:
2759 self.a = 1
2760
2761 def b(self) -> int:
2762 return 2
2763
2764 @property
2765 def c(self) -> int:
2766 return 3
2767
2768 def test_class_final_attribute() -> None:
2769 assert C().a == 1
2770 assert C().b() == 2
2771 assert C().c == 3
2772
2773 [case testClassWithFinalDecoratorInheritedWithProperties]
2774 from typing import final
2775
2776 class B:
2777 def a(self) -> int:
2778 return 2
2779
2780 @property
2781 def b(self) -> int:
2782 return self.a() + 2
2783
2784 @property
2785 def c(self) -> int:
2786 return 3
2787
2788 def test_class_final_attribute_basic() -> None:
2789 assert B().a() == 2
2790 assert B().b == 4
2791 assert B().c == 3
2792
2793 @final
2794 class C(B):
2795 def a(self) -> int:
2796 return 1
2797
2798 @property
2799 def b(self) -> int:
2800 return self.a() + 1
2801
2802 def fn(cl: B) -> int:
2803 return cl.a()
2804
2805 def test_class_final_attribute_inherited() -> None:
2806 assert C().a() == 1
2807 assert fn(C()) == 1
2808 assert B().a() == 2
2809 assert fn(B()) == 2
2810
2811 assert B().b == 4
2812 assert C().b == 2
2813 assert B().c == 3
2814 assert C().c == 3
2815
2816 [case testClassWithFinalAttributeAccess]
2817 from typing import Final
2818
2819 class C:
2820 a: Final = {'x': 'y'}
2821 b: Final = C.a
2822
2823 def test_final_attribute() -> None:
2824 assert C.a['x'] == 'y'
2825 assert C.b['x'] == 'y'
2826 assert C.a is C.b
2827
2828 [case testFinalInstanceAttributeCannotBeRebound]
2829 from typing import Any, Final
2830
2831 from testutil import assertRaises
2832
2833 class C:
2834 def __init__(self, x: int) -> None:
2835 self.x: Final[int] = x
2836
2837 class D(C):
2838 def __init__(self, x: int, y: int) -> None:
2839 super().__init__(x)
2840 self.y: Final[int] = y
2841
2842 def rebind_via_any(o: Any, value: int) -> None:
2843 o.x = value
2844
2845 def test_rebind_via_any() -> None:
2846 c = C(1)
2847 with assertRaises(AttributeError):
2848 rebind_via_any(c, 2)
2849 assert c.x == 1
2850
2851 def test_rebind_via_setattr() -> None:
2852 c = C(1)
2853 with assertRaises(AttributeError):
2854 setattr(c, "x", 3)
2855 assert c.x == 1
2856
2857 def test_rebind_inherited_via_setattr() -> None:
2858 d = D(1, 2)
2859 # Inherited Final attribute can't be modified.
2860 with assertRaises(AttributeError):
2861 setattr(d, "x", 3)
2862 # The subclass's own Final attribute can't be modified either.
2863 with assertRaises(AttributeError):
2864 setattr(d, "y", 4)
2865 assert d.x == 1
2866 assert d.y == 2
2867
2868 [case testFinalRefcountedAttributeRead]
2869 # Exercises reading Final reference-counted ('PyObject *') attributes, which on
2870 # free-threaded builds use a faster read path (CPy_GetAttrRefFinal) that skips the
2871 # concurrent-writer guard, since a Final attribute is never rebound.
2872 from typing import Final
2873
2874 class C:
2875 def __init__(self, s: str, items: list[int]) -> None:
2876 self.s: Final = s
2877 self.items: Final = items
2878
2879 def read_s(self) -> str:
2880 return self.s
2881
2882 def read_items(self) -> list[int]:
2883 return self.items
2884
2885 def chained_len(self) -> int:
2886 # borrowed intermediate read of a Final attr, then a call on it
2887 return len(self.items)
2888
2889 class D(C):
2890 def __init__(self, s: str, items: list[int], t: str) -> None:
2891 super().__init__(s, items)
2892 self.t: Final = t
2893
2894 def read_inherited(self) -> str:
2895 return self.s
2896
2897 def test_read_final_object_attrs() -> None:
2898 c = C("hello", [1, 2, 3])
2899 # Read via getter (property access) and via native method bodies.
2900 assert c.s == "hello"
2901 assert c.read_s() == "hello"
2902 assert c.items == [1, 2, 3]
2903 assert c.read_items() == [1, 2, 3]
2904 assert c.chained_len() == 3
2905 # Reading repeatedly must not corrupt the refcount / free the value.
2906 for _ in range(1000):
2907 assert c.read_s() == "hello"
2908 assert c.read_items() == [1, 2, 3]
2909 assert c.s == "hello"
2910 assert c.read_items() is c.items
2911
2912 def test_read_inherited_final_attr() -> None:
2913 d = D("a", [4, 5], "b")
2914 assert d.s == "a"
2915 assert d.t == "b"
2916 assert d.read_s() == "a"
2917 assert d.read_inherited() == "a"
2918 assert d.read_items() == [4, 5]
2919
2920 [case testClassDerivedFromIntEnum]
2921 from enum import IntEnum, auto
2922
2923 class Player(IntEnum):
2924 MIN = auto()
2925
2926 print(f'{Player.MIN = }')
2927 [file driver.py]
2928 from native import Player
2929 [out]
2930 Player.MIN = <Player.MIN: 1>
2931
2932 [case testBufferRoundTrip_librt_internal]
2933 from __future__ import annotations
2934
2935 from typing import Final, Any
2936 from mypy_extensions import u8
2937 from librt.internal import (
2938 ReadBuffer, WriteBuffer, write_bool, read_bool, write_str, read_str, write_float, read_float,
2939 write_int, read_int, write_tag, read_tag, write_bytes, read_bytes,
2940 cache_version,
2941 )
2942
2943 from testutil import assertRaises
2944
2945 Tag = u8
2946 TAG_A: Final[Tag] = 33
2947 TAG_B: Final[Tag] = 255
2948 TAG_SPECIAL: Final[Tag] = 239
2949
2950 def test_buffer_basic() -> None:
2951 assert cache_version() == 0
2952 w = WriteBuffer()
2953 write_str(w, "foo")
2954 r = ReadBuffer(w.getvalue())
2955 assert read_str(r) == "foo"
2956
2957 def test_buffer_grow() -> None:
2958 w = WriteBuffer()
2959 n = 100 * 1000
2960 for i in range(n):
2961 write_int(w, i & 63)
2962 r = ReadBuffer(w.getvalue())
2963 for i in range(n):
2964 assert read_int(r) == (i & 63)
2965 with assertRaises(ValueError):
2966 read_int(r)
2967
2968 def test_buffer_primitive_types() -> None:
2969 a1: Any = WriteBuffer()
2970 w: WriteBuffer = a1
2971 write_str(w, "foo")
2972 data = w.getvalue()
2973 assert read_str(ReadBuffer(data)) == "foo"
2974 a2: Any = ReadBuffer(b"foo")
2975 with assertRaises(TypeError):
2976 w2: WriteBuffer = a2
2977
2978 a3: Any = ReadBuffer(data)
2979 r: ReadBuffer = a3
2980 assert read_str(r) == "foo"
2981 a4: Any = WriteBuffer()
2982 with assertRaises(TypeError):
2983 r2: ReadBuffer = a4
2984
2985 def test_type_check_args_in_write_functions() -> None:
2986 # Test calling wrapper functions with invalid arg types
2987 from librt import internal
2988 alias: Any = internal
2989 w = WriteBuffer()
2990 with assertRaises(TypeError):
2991 alias.write_str(None, "foo")
2992 with assertRaises(TypeError):
2993 alias.write_str(w, None)
2994 with assertRaises(TypeError):
2995 alias.write_bool(None, True)
2996 with assertRaises(TypeError):
2997 alias.write_bool(w, None)
2998 with assertRaises(TypeError):
2999 alias.write_bytes(None, b"foo")
3000 with assertRaises(TypeError):
3001 alias.write_bytes(w, None)
3002 with assertRaises(TypeError):
3003 alias.write_float(None, 1.5)
3004 with assertRaises(TypeError):
3005 alias.write_float(w, None)
3006 with assertRaises(TypeError):
3007 alias.write_int(None, 15)
3008 with assertRaises(TypeError):
3009 alias.write_int(w, None)
3010 with assertRaises(TypeError):
3011 alias.write_tag(None, 15)
3012 with assertRaises(TypeError):
3013 alias.write_tag(w, None)
3014
3015 def test_type_check_buffer_in_read_functions() -> None:
3016 # Test calling wrapper functions with invalid arg types
3017 from librt import internal
3018 alias: Any = internal
3019 with assertRaises(TypeError):
3020 alias.read_str(None)
3021 with assertRaises(TypeError):
3022 alias.read_bool(None)
3023 with assertRaises(TypeError):
3024 alias.read_bytes(None)
3025 with assertRaises(TypeError):
3026 alias.read_float(None)
3027 with assertRaises(TypeError):
3028 alias.read_int(None)
3029 with assertRaises(TypeError):
3030 alias.read_tag(None)
3031
3032 def test_buffer_roundtrip() -> None:
3033 b: WriteBuffer | ReadBuffer
3034 b = WriteBuffer()
3035 write_str(b, "foo")
3036 write_bool(b, True)
3037 write_str(b, "bar" * 1000)
3038 write_bool(b, False)
3039 write_bytes(b, b"bar")
3040 write_bytes(b, b"bar" * 100)
3041 write_bytes(b, b"")
3042 write_bytes(b, b"a" * 117)
3043 write_bytes(b, b"a" * 118)
3044 write_float(b, 0.1)
3045 write_float(b, -1.0)
3046 write_float(b, -113.0)
3047 write_int(b, 0)
3048 write_int(b, 1)
3049 write_tag(b, TAG_A)
3050 write_tag(b, TAG_SPECIAL)
3051 write_tag(b, TAG_B)
3052 write_int(b, 2)
3053 write_int(b, 2 ** 85)
3054 write_int(b, 255)
3055 write_int(b, -1)
3056 write_int(b, -255)
3057 write_int(b, 536860911)
3058 write_int(b, 536860912)
3059 write_int(b, 1234567891)
3060
3061 b = ReadBuffer(b.getvalue())
3062 assert read_str(b) == "foo"
3063 assert read_bool(b) is True
3064 assert read_str(b) == "bar" * 1000
3065 assert read_bool(b) is False
3066 assert read_bytes(b) == b"bar"
3067 assert read_bytes(b) == b"bar" * 100
3068 assert read_bytes(b) == b""
3069 assert read_bytes(b) == b"a" * 117
3070 assert read_bytes(b) == b"a" * 118
3071 assert read_float(b) == 0.1
3072 assert read_float(b) == -1.0
3073 assert read_float(b) == -113.0
3074 assert read_int(b) == 0
3075 assert read_int(b) == 1
3076 assert read_tag(b) == TAG_A
3077 assert read_tag(b) == TAG_SPECIAL
3078 assert read_tag(b) == TAG_B
3079 assert read_int(b) == 2
3080 assert read_int(b) == 2 ** 85
3081 assert read_int(b) == 255
3082 assert read_int(b) == -1
3083 assert read_int(b) == -255
3084 assert read_int(b) == 536860911
3085 assert read_int(b) == 536860912
3086 assert read_int(b) == 1234567891
3087
3088 def test_buffer_int_size() -> None:
3089 b: WriteBuffer | ReadBuffer
3090 for i in (-10, -9, 0, 116, 117):
3091 b = WriteBuffer()
3092 write_int(b, i)
3093 assert len(b.getvalue()) == 1
3094 b = ReadBuffer(b.getvalue())
3095 assert read_int(b) == i
3096 for i in (-100, -11, 118, 12344, 16283):
3097 b = WriteBuffer()
3098 write_int(b, i)
3099 assert len(b.getvalue()) == 2
3100 b = ReadBuffer(b.getvalue())
3101 assert read_int(b) == i
3102 for i in (-10000, 16284, 123456789):
3103 b = WriteBuffer()
3104 write_int(b, i)
3105 assert len(b.getvalue()) == 4
3106 b = ReadBuffer(b.getvalue())
3107 assert read_int(b) == i
3108
3109 def test_buffer_int_powers() -> None:
3110 # 0, 1, 2 are tested above
3111 for p in range(2, 200):
3112 b = WriteBuffer()
3113 write_int(b, 1 << p)
3114 write_int(b, (1 << p) - 1)
3115 write_int(b, -1 << p)
3116 write_int(b, (-1 << p) + 1)
3117 rb = ReadBuffer(b.getvalue())
3118 assert read_int(rb) == 1 << p
3119 assert read_int(rb) == (1 << p) - 1
3120 assert read_int(rb) == -1 << p
3121 assert read_int(rb) == (-1 << p) + 1
3122
3123 def test_positive_long_int_serialized_bytes() -> None:
3124 b = WriteBuffer()
3125 n = 0x123456789ab
3126 write_int(b, n)
3127 x = b.getvalue()
3128 # Two prefix bytes, followed by little endian encoded integer in variable-length format
3129 assert x == b"\x0f\x2c\xab\x89\x67\x45\x23\x01"
3130 rb = ReadBuffer(x)
3131 assert read_int(rb) == n
3132
3133 def test_negative_long_int_serialized_bytes() -> None:
3134 b = WriteBuffer()
3135 n = -0x123456789abcde
3136 write_int(b, n)
3137 x = b.getvalue()
3138 assert x == b"\x0f\x32\xde\xbc\x9a\x78\x56\x34\x12"
3139 rb = ReadBuffer(x)
3140 assert read_int(rb) == n
3141
3142 def test_buffer_str_size() -> None:
3143 b: WriteBuffer | ReadBuffer
3144 for s in ("", "a", "a" * 117):
3145 b = WriteBuffer()
3146 write_str(b, s)
3147 assert len(b.getvalue()) == len(s) + 1
3148 b = ReadBuffer(b.getvalue())
3149 assert read_str(b) == s
3150
3151 for s in ("a" * 118, "a" * 16283):
3152 b = WriteBuffer()
3153 write_str(b, s)
3154 assert len(b.getvalue()) == len(s) + 2
3155 b = ReadBuffer(b.getvalue())
3156 assert read_str(b) == s
3157
3158 [file driver.py]
3159 from native import *
3160
3161 test_buffer_basic()
3162 test_buffer_grow()
3163 test_buffer_primitive_types()
3164 test_type_check_args_in_write_functions()
3165 test_type_check_buffer_in_read_functions()
3166 test_buffer_roundtrip()
3167 test_buffer_int_size()
3168 test_buffer_str_size()
3169 test_buffer_int_powers()
3170 test_positive_long_int_serialized_bytes()
3171 test_negative_long_int_serialized_bytes()
3172
3173 def test_buffer_basic_interpreted() -> None:
3174 b = WriteBuffer()
3175 write_str(b, "foo")
3176 b = ReadBuffer(b.getvalue())
3177 assert read_str(b) == "foo"
3178
3179 def test_buffer_roundtrip_interpreted() -> None:
3180 b = WriteBuffer()
3181 write_str(b, "foo")
3182 write_bool(b, True)
3183 write_str(b, "bar" * 1000)
3184 write_bool(b, False)
3185 write_bytes(b, b"bar")
3186 write_bytes(b, b"bar" * 100)
3187 write_bytes(b, b"")
3188 write_bytes(b, b"a" * 117)
3189 write_bytes(b, b"a" * 118)
3190 write_float(b, 0.1)
3191 write_int(b, 0)
3192 write_int(b, 1)
3193 write_tag(b, 33)
3194 write_tag(b, 239)
3195 write_tag(b, 255)
3196 write_int(b, 2)
3197 write_int(b, 2 ** 85)
3198 write_int(b, 255)
3199 write_int(b, -1)
3200 write_int(b, -255)
3201 write_int(b, 536860911)
3202 write_int(b, 536860912)
3203 write_int(b, 1234567891)
3204
3205 b = ReadBuffer(b.getvalue())
3206 assert read_str(b) == "foo"
3207 assert read_bool(b) is True
3208 assert read_str(b) == "bar" * 1000
3209 assert read_bool(b) is False
3210 assert read_bytes(b) == b"bar"
3211 assert read_bytes(b) == b"bar" * 100
3212 assert read_bytes(b) == b""
3213 assert read_bytes(b) == b"a" * 117
3214 assert read_bytes(b) == b"a" * 118
3215 assert read_float(b) == 0.1
3216 assert read_int(b) == 0
3217 assert read_int(b) == 1
3218 assert read_tag(b) == 33
3219 assert read_tag(b) == 239
3220 assert read_tag(b) == 255
3221 assert read_int(b) == 2
3222 assert read_int(b) == 2 ** 85
3223 assert read_int(b) == 255
3224 assert read_int(b) == -1
3225 assert read_int(b) == -255
3226 assert read_int(b) == 536860911
3227 assert read_int(b) == 536860912
3228 assert read_int(b) == 1234567891
3229
3230 def test_buffer_int_size_interpreted() -> None:
3231 for i in (-10, -9, 0, 116, 117):
3232 b = WriteBuffer()
3233 write_int(b, i)
3234 assert len(b.getvalue()) == 1
3235 b = ReadBuffer(b.getvalue())
3236 assert read_int(b) == i
3237 for i in (-100, -11, 118, 12344, 16283):
3238 b = WriteBuffer()
3239 write_int(b, i)
3240 assert len(b.getvalue()) == 2
3241 b = ReadBuffer(b.getvalue())
3242 assert read_int(b) == i
3243 for i in (-10000, 16284, 123456789):
3244 b = WriteBuffer()
3245 write_int(b, i)
3246 assert len(b.getvalue()) == 4
3247 b = ReadBuffer(b.getvalue())
3248 assert read_int(b) == i
3249
3250 def test_buffer_int_powers_interpreted() -> None:
3251 # 0, 1, 2 are tested above
3252 for p in range(2, 9):
3253 b = WriteBuffer()
3254 write_int(b, 1 << p)
3255 write_int(b, -1 << p)
3256 b = ReadBuffer(b.getvalue())
3257 assert read_int(b) == 1 << p
3258 assert read_int(b) == -1 << p
3259
3260 def test_buffer_str_size_interpreted() -> None:
3261 for s in ("", "a", "a" * 117):
3262 b = WriteBuffer()
3263 write_str(b, s)
3264 assert len(b.getvalue()) == len(s) + 1
3265 b = ReadBuffer(b.getvalue())
3266 assert read_str(b) == s
3267
3268 for s in ("a" * 118, "a" * 16283):
3269 b = WriteBuffer()
3270 write_str(b, s)
3271 assert len(b.getvalue()) == len(s) + 2
3272 b = ReadBuffer(b.getvalue())
3273 assert read_str(b) == s
3274
3275 test_buffer_basic_interpreted()
3276 test_buffer_roundtrip_interpreted()
3277 test_buffer_int_size_interpreted()
3278 test_buffer_str_size_interpreted()
3279 test_buffer_int_powers_interpreted()
3280
3281 [case testBufferEmpty_librt_internal]
3282 from librt.internal import WriteBuffer, ReadBuffer, write_int, read_int
3283
3284 def test_empty() -> None:
3285 b = WriteBuffer()
3286 write_int(b, 42)
3287 b1 = ReadBuffer(b.getvalue())
3288 assert read_int(b1) == 42
3289
3290 [case testEnumMethodCalls]
3291 from enum import Enum
3292 from typing import overload, Optional, Union
3293
3294 class C:
3295 def foo(self, x: Test) -> bool:
3296 assert Test.ONE.is_one()
3297 assert x.next(2) == Test.THREE
3298 assert x.prev(2) == Test.ONE
3299 assert x.enigma(22)
3300 assert x.enigma("22") == 22
3301 return x.is_one(inverse=True)
3302
3303 class Test(Enum):
3304 ONE = 1
3305 TWO = 2
3306 THREE = 3
3307
3308 def is_one(self, *, inverse: bool = False) -> bool:
3309 if inverse:
3310 return self != Test.ONE
3311 return self == Test.ONE
3312
3313 @classmethod
3314 def next(cls, val: int) -> Test:
3315 return cls(val + 1)
3316
3317 @staticmethod
3318 def prev(val: int) -> Test:
3319 return Test(val - 1)
3320
3321 @overload
3322 def enigma(self, val: int) -> bool: ...
3323 @overload
3324 def enigma(self, val: Optional[str] = None) -> int: ...
3325 def enigma(self, val: Union[int, str, None] = None) -> Union[int, bool]:
3326 if isinstance(val, int):
3327 return self.is_one()
3328 return 22
3329 [file driver.py]
3330 from native import Test, C
3331
3332 assert Test.ONE.is_one()
3333 assert Test.TWO.is_one(inverse=True)
3334 assert not C().foo(Test.ONE)
3335 assert Test.next(2) == Test.THREE
3336 assert Test.prev(2) == Test.ONE
3337 assert Test.ONE.enigma(22)
3338 assert Test.ONE.enigma("22") == 22
3339
3340 [case testStaticCallsWithUnpackingArgs]
3341 from typing import Tuple
3342
3343 class Foo:
3344 @staticmethod
3345 def static(a: int, b: int, c: int) -> Tuple[int, int, int]:
3346 return (c+1, a+2, b+3)
3347
3348 @classmethod
3349 def clsmethod(cls, a: int, b: int, c: int) -> Tuple[int, int, int]:
3350 return (c+1, a+2, b+3)
3351
3352
3353 print(Foo.static(*[10, 20, 30]))
3354 print(Foo.static(*(40, 50), *[60]))
3355 assert Foo.static(70, 80, *[90]) == Foo.clsmethod(70, *(80, 90))
3356
3357 [file driver.py]
3358 import native
3359
3360 [out]
3361 (31, 12, 23)
3362 (61, 42, 53)
3363
3364 [case testDataclassInitVar]
3365 import dataclasses
3366
3367 @dataclasses.dataclass
3368 class C:
3369 init_v: dataclasses.InitVar[int]
3370 v: float = dataclasses.field(init=False)
3371
3372 def __post_init__(self, init_v):
3373 self.v = init_v + 0.1
3374
3375 [file driver.py]
3376 import native
3377 print(native.C(22).v)
3378
3379 [out]
3380 22.1
3381
3382 [case testLastParentEnum]
3383 from enum import Enum
3384
3385 class ColorCode(str, Enum):
3386 OKGREEN = "okgreen"
3387
3388 [file driver.py]
3389 import native
3390 print(native.ColorCode.OKGREEN.value)
3391
3392 [out]
3393 okgreen
3394
3395 [case testAttrWithSlots]
3396 import attr
3397
3398 @attr.s(slots=True)
3399 class A:
3400 ints: list[int] = attr.ib()
3401
3402 [file driver.py]
3403 import native
3404 print(native.A(ints=[1, -17]).ints)
3405
3406 [out]
3407 \[1, -17]
3408
3409 [case testDataclassClassReference]
3410 from __future__ import annotations
3411 from dataclasses import dataclass
3412
3413 class BackwardDefinedClass:
3414 pass
3415
3416 @dataclass
3417 class Data:
3418 bitem: BackwardDefinedClass
3419 bitems: 'BackwardDefinedClass'
3420 fitem: ForwardDefinedClass
3421 fitems: 'ForwardDefinedClass'
3422
3423 class ForwardDefinedClass:
3424 pass
3425
3426 def test_function():
3427 d = Data(
3428 bitem=BackwardDefinedClass(),
3429 bitems=BackwardDefinedClass(),
3430 fitem=ForwardDefinedClass(),
3431 fitems=ForwardDefinedClass(),
3432 )
3433 assert(isinstance(d.bitem, BackwardDefinedClass))
3434 assert(isinstance(d.bitems, BackwardDefinedClass))
3435 assert(isinstance(d.fitem, ForwardDefinedClass))
3436 assert(isinstance(d.fitems, ForwardDefinedClass))
3437
3438 [case testDelForDictSubclass]
3439 events: list[str] = []
3440
3441 class Item:
3442 def __del__(self) -> None:
3443 events.append("deleting Item")
3444
3445 class DictSubclass(dict):
3446 def __del__(self) -> None:
3447 events.append("deleting DictSubclass")
3448
3449 def test_dict_subclass_dealloc() -> None:
3450 d = DictSubclass()
3451 d["item"] = Item()
3452 del d
3453
3454 [file driver.py]
3455 import sys
3456
3457 from native import events, test_dict_subclass_dealloc
3458
3459 test_dict_subclass_dealloc()
3460
3461 expected_events: list[str] = []
3462
3463 # TODO: Fix when compiling for older python.
3464 # The user-defined __del__ method is currently only invoked when __dict__ is a managed dict
3465 # because calling __del__ in tp_clear on older python crashes.
3466 if sys.version_info >= (3, 12):
3467 expected_events.append("deleting DictSubclass")
3468 expected_events.append("deleting Item")
3469
3470 assert events == expected_events, events
3471
3472 [case testDel]
3473 class A:
3474 def __del__(self):
3475 print("deleting A...")
3476
3477 class B:
3478 def __del__(self):
3479 print("deleting B...")
3480
3481 class C(B):
3482 def __init__(self):
3483 self.a = A()
3484
3485 def __del__(self):
3486 print("deleting C...")
3487 super().__del__()
3488
3489 class D(A):
3490 pass
3491
3492 # Just make sure that this class compiles (see issue mypy#19175). testDelForDictSubclass tests for
3493 # correct output.
3494 class NormDict(dict):
3495 def __del__(self) -> None:
3496 pass
3497
3498 [file driver.py]
3499 import native
3500 native.C()
3501 native.D()
3502
3503 [out]
3504 deleting C...
3505 deleting B...
3506 deleting A...
3507 deleting A...
3508
3509 [case testDelCircular]
3510 import dataclasses
3511 import typing
3512
3513 i: int = 1
3514
3515 @dataclasses.dataclass
3516 class C:
3517 var: typing.Optional["C"] = dataclasses.field(default=None)
3518
3519 def __del__(self):
3520 global i
3521 print(f"deleting C{i}...")
3522 i = i + 1
3523
3524 [file driver.py]
3525 import native
3526 import gc
3527
3528 c1 = native.C()
3529 c2 = native.C()
3530 c1.var = c2
3531 c2.var = c1
3532 del c1
3533 del c2
3534 gc.collect()
3535
3536 [out]
3537 deleting C1...
3538 deleting C2...
3539
3540 [case testDelException]
3541 # The error message in the expected output of this test does not match CPython's error message due to the way mypyc compiles Python classes. If the error message is fixed, the expected output of this test will also change.
3542 class F:
3543 def __del__(self):
3544 if True:
3545 raise Exception("e2")
3546
3547 [file driver.py]
3548 import native
3549 f = native.F()
3550 del f
3551
3552 [out]
3553 Exception ignored in: <native.F object at 0x000000000000>
3554 Traceback (most recent call last):
3555 File "native.py", line 5, in __del__
3556 raise Exception("e2")
3557 Exception: e2
3558
3559 [case testMypycAttrNativeClass]
3560 from mypy_extensions import mypyc_attr
3561 from testutil import assertRaises
3562
3563 @mypyc_attr(native_class=False)
3564 class AnnontatedNonExtensionClass:
3565 pass
3566
3567 class DerivedClass(AnnontatedNonExtensionClass):
3568 pass
3569
3570 class ImplicitExtensionClass():
3571 pass
3572
3573 @mypyc_attr(native_class=True)
3574 class AnnotatedExtensionClass():
3575 pass
3576
3577 def test_function():
3578 setattr(AnnontatedNonExtensionClass, 'attr_class', 5)
3579 assert(hasattr(AnnontatedNonExtensionClass, 'attr_class') == True)
3580 assert(getattr(AnnontatedNonExtensionClass, 'attr_class') == 5)
3581 delattr(AnnontatedNonExtensionClass, 'attr_class')
3582 assert(hasattr(AnnontatedNonExtensionClass, 'attr_class') == False)
3583
3584 inst = AnnontatedNonExtensionClass()
3585 setattr(inst, 'attr_instance', 6)
3586 assert(hasattr(inst, 'attr_instance') == True)
3587 assert(getattr(inst, 'attr_instance') == 6)
3588 delattr(inst, 'attr_instance')
3589 assert(hasattr(inst, 'attr_instance') == False)
3590
3591 setattr(DerivedClass, 'attr_class', 5)
3592 assert(hasattr(DerivedClass, 'attr_class') == True)
3593 assert(getattr(DerivedClass, 'attr_class') == 5)
3594 delattr(DerivedClass, 'attr_class')
3595 assert(hasattr(DerivedClass, 'attr_class') == False)
3596
3597 derived_inst = DerivedClass()
3598 setattr(derived_inst, 'attr_instance', 6)
3599 assert(hasattr(derived_inst, 'attr_instance') == True)
3600 assert(getattr(derived_inst, 'attr_instance') == 6)
3601 delattr(derived_inst, 'attr_instance')
3602 assert(hasattr(derived_inst, 'attr_instance') == False)
3603
3604 ext_inst = ImplicitExtensionClass()
3605 with assertRaises(AttributeError):
3606 setattr(ext_inst, 'attr_instance', 6)
3607
3608 explicit_ext_inst = AnnotatedExtensionClass()
3609 with assertRaises(AttributeError):
3610 setattr(explicit_ext_inst, 'attr_instance', 6)
3611
3612 [case testMypycAttrNativeClassDunder]
3613 from mypy_extensions import mypyc_attr
3614 from typing import Generic, Optional, TypeVar
3615
3616 _T = TypeVar("_T")
3617
3618 get_count = set_count = del_count = 0
3619
3620 @mypyc_attr(native_class=False)
3621 class Bar(Generic[_T]):
3622 # Note the lack of __deletable__
3623 def __init__(self) -> None:
3624 self.value: str = 'start'
3625 def __get__(self, instance: _T, owner: Optional[type[_T]] = None) -> str:
3626 global get_count
3627 get_count += 1
3628 return self.value
3629 def __set__(self, instance: _T, value: str) -> None:
3630 global set_count
3631 set_count += 1
3632 self.value = value
3633 def __delete__(self, instance: _T) -> None:
3634 global del_count
3635 del_count += 1
3636 del self.value
3637
3638 @mypyc_attr(native_class=False)
3639 class Foo(object):
3640 bar: Bar = Bar()
3641
3642 [file driver.py]
3643 import native
3644
3645 f = native.Foo()
3646 assert(hasattr(f, 'bar'))
3647 assert(native.get_count == 1)
3648 assert(f.bar == 'start')
3649 assert(native.get_count == 2)
3650 f.bar = 'test'
3651 assert(f.bar == 'test')
3652 assert(native.set_count == 1)
3653 del f.bar
3654 assert(not hasattr(f, 'bar'))
3655 assert(native.del_count == 1)
3656
3657 [case testMypycAttrNativeClassMeta]
3658 from mypy_extensions import mypyc_attr
3659 from typing import ClassVar, TypeVar
3660
3661 _T = TypeVar("_T")
3662
3663 @mypyc_attr(native_class=False)
3664 class M(type):
3665 count: ClassVar[int] = 0
3666 def make(cls: type[_T]) -> _T:
3667 M.count += 1
3668 return cls()
3669
3670 # implicit native_class=False
3671 # see testMypycAttrNativeClassMetaError for when trying to set it True
3672 class A(metaclass=M):
3673 pass
3674
3675 [file driver.py]
3676 import native
3677
3678 a: native.A = native.A.make()
3679 assert(native.A.count == 1)
3680
3681 class B(native.A):
3682 pass
3683
3684 b: B = B.make()
3685 assert(B.count == 2)
3686
3687 [case testTypeVarNarrowing]
3688 from typing import TypeVar
3689
3690 class B:
3691 def __init__(self, x: int) -> None:
3692 self.x = x
3693 class C(B):
3694 def __init__(self, x: int, y: str) -> None:
3695 self.x = x
3696 self.y = y
3697
3698 T = TypeVar("T", bound=B)
3699 def f(x: T) -> T:
3700 if isinstance(x, C):
3701 print("C", x.y)
3702 return x
3703 print("B", x.x)
3704 return x
3705
3706 [file driver.py]
3707 from native import f, B, C
3708
3709 f(B(1))
3710 f(C(1, "yes"))
3711 [out]
3712 B 1
3713 C yes
3714
3715 [case testTypeObjectName]
3716 from typing import Any
3717 import re
3718
3719 from dynamic import E, foo, Thing
3720
3721 class C: pass
3722 class D(C): pass
3723
3724 def type_name(t: type[object]) -> str:
3725 return t.__name__
3726
3727 def any_name(x: Any) -> str:
3728 return x.__name__
3729
3730 def assert_type_name(x: Any) -> None:
3731 assert type_name(x) == getattr(x, "__name__")
3732 assert any_name(x) == getattr(x, "__name__")
3733
3734 def assert_any_name(x: Any) -> None:
3735 assert any_name(x) == getattr(x, "__name__")
3736
3737 def test_type_name() -> None:
3738 assert_type_name(C)
3739 assert_type_name(D)
3740 assert_type_name(int)
3741 assert_type_name(E)
3742 assert_type_name(re.Pattern)
3743
3744 def test_module_name() -> None:
3745 assert_any_name(re)
3746
3747 def test_function_name() -> None:
3748 assert_any_name(any_name)
3749 assert_any_name(foo)
3750
3751 def test_obj_name() -> None:
3752 assert_any_name(Thing())
3753
3754 [file dynamic.py]
3755 class E: pass
3756
3757 def foo(): pass
3758
3759 class Thing:
3760 def __init__(self):
3761 self.__name__ = "xyz"
3762
3763 [case testTypeOfObject]
3764 from typing import Any
3765
3766 from dynamic import Dyn
3767
3768 class Foo: pass
3769 class Bar(Foo): pass
3770
3771 def generic_type(x) -> type[object]:
3772 return x.__class__
3773
3774 def test_built_in_type() -> None:
3775 i: Any = int
3776 l: Any = list
3777 assert type(i()) is i().__class__
3778 assert type(i()) is int
3779 assert type(l()) is list
3780 n = 5
3781 assert n.__class__ is i
3782
3783 def test_native_class() -> None:
3784 f_any: Any = Foo()
3785 b_any: Any = Bar()
3786 f: Foo = f_any
3787 b: Foo = b_any
3788 if int("1"): # use int("1") to avoid constant folding
3789 assert type(f) is Foo
3790 assert type(b) is Bar
3791 if int("2"):
3792 assert f.__class__ is Foo
3793 assert b.__class__ is Bar
3794 if int("3"):
3795 assert f_any.__class__ is Foo
3796 assert b_any.__class__ is Bar
3797 if int("4"):
3798 assert type(f_any) is Foo
3799 assert type(b_any) is Bar
3800
3801 def test_python_class() -> None:
3802 d = Dyn()
3803 assert type(d) is Dyn
3804 assert d.__class__ is Dyn
3805
3806 [file dynamic.py]
3807 class Dyn: pass
3808
3809 [case testDunderNew]
3810 from __future__ import annotations
3811 from typing import Any, Union
3812
3813 from testutil import assertRaises
3814
3815 class Add:
3816 l: IntLike
3817 r: IntLike
3818
3819 def __new__(cls, l: IntLike, r: IntLike) -> Any:
3820 return (
3821 l if r == 0 else
3822 r if l == 0 else
3823 super().__new__(cls)
3824 )
3825
3826 def __init__(self, l: IntLike, r: IntLike):
3827 self.l = l
3828 self.r = r
3829
3830 IntLike = Union[int, Add]
3831
3832 class RaisesException:
3833 def __new__(cls, val: int) -> RaisesException:
3834 if val == 0:
3835 raise RuntimeError("Invalid value!")
3836 return super().__new__(cls)
3837
3838 def __init__(self, val: int) -> None:
3839 self.val = val
3840
3841 class ClsArgNotPassed:
3842 def __new__(cls) -> Any:
3843 return super().__new__(str)
3844
3845 def test_dunder_new() -> None:
3846 add_instance: Any = Add(1, 5)
3847 assert type(add_instance) == Add
3848 assert add_instance.l == 1
3849 assert add_instance.r == 5
3850
3851 # TODO: explicit types should not be needed but mypy does not use
3852 # the return type of __new__ which makes mypyc add casts to Add.
3853 right_int: Any = Add(0, 5)
3854 assert type(right_int) == int
3855 assert right_int == 5
3856
3857 left_int: Any = Add(1, 0)
3858 assert type(left_int) == int
3859 assert left_int == 1
3860
3861 with assertRaises(RuntimeError, "Invalid value!"):
3862 raised = RaisesException(0)
3863
3864 not_raised = RaisesException(1)
3865 assert not_raised.val == 1
3866
3867 with assertRaises(TypeError, "object.__new__(str) is not safe, use str.__new__()"):
3868 str_as_cls = ClsArgNotPassed()
3869
3870
3871 [case testDunderNewInInterpreted]
3872 from __future__ import annotations
3873 from typing import Any, Union
3874
3875 class Add:
3876 l: IntLike
3877 r: IntLike
3878
3879 def __new__(cls, l: IntLike, r: IntLike) -> Any:
3880 print(f'running __new__ with {l} and {r}')
3881
3882 return (
3883 l if r == 0 else
3884 r if l == 0 else
3885 super().__new__(cls)
3886 )
3887
3888 def __init__(self, l: IntLike, r: IntLike):
3889 self.l = l
3890 self.r = r
3891
3892 def __repr__(self) -> str:
3893 return f'({self.l} + {self.r})'
3894
3895 IntLike = Union[int, Add]
3896
3897 class RaisesException:
3898 def __new__(cls, val: int) -> RaisesException:
3899 if val == 0:
3900 raise RuntimeError("Invalid value!")
3901 return super().__new__(cls)
3902
3903 def __init__(self, val: int) -> None:
3904 self.val = val
3905
3906 class ClsArgNotPassed:
3907 def __new__(cls) -> Any:
3908 return super().__new__(str)
3909
3910 [file driver.py]
3911 from native import Add, ClsArgNotPassed, RaisesException
3912
3913 from testutil import assertRaises
3914
3915 print(f'{Add(1, 5)=}')
3916 print(f'{Add(0, 5)=}')
3917 print(f'{Add(1, 0)=}')
3918
3919 with assertRaises(RuntimeError, "Invalid value!"):
3920 raised = RaisesException(0)
3921
3922 not_raised = RaisesException(1)
3923 assert not_raised.val == 1
3924
3925 with assertRaises(TypeError, "object.__new__(str) is not safe, use str.__new__()"):
3926 str_as_cls = ClsArgNotPassed()
3927
3928 [out]
3929 running __new__ with 1 and 5
3930 Add(1, 5)=(1 + 5)
3931 running __new__ with 0 and 5
3932 Add(0, 5)=5
3933 running __new__ with 1 and 0
3934 Add(1, 0)=1
3935
3936 [case testObjectDunderNew]
3937 from __future__ import annotations
3938 from typing import Any, Union
3939
3940 from testutil import assertRaises
3941
3942 class Add:
3943 l: IntLike
3944 r: IntLike
3945
3946 def __new__(cls, l: IntLike, r: IntLike) -> Any:
3947 return (
3948 l if r == 0 else
3949 r if l == 0 else
3950 object.__new__(cls)
3951 )
3952
3953 def __init__(self, l: IntLike, r: IntLike):
3954 self.l = l
3955 self.r = r
3956
3957 IntLike = Union[int, Add]
3958
3959 class RaisesException:
3960 def __new__(cls, val: int) -> RaisesException:
3961 if val == 0:
3962 raise RuntimeError("Invalid value!")
3963 return object.__new__(cls)
3964
3965 def __init__(self, val: int) -> None:
3966 self.val = val
3967
3968 class ClsArgNotPassed:
3969 def __new__(cls) -> Any:
3970 return object.__new__(str)
3971
3972 class SkipsBase(Add):
3973 def __new__(cls) -> Any:
3974 obj = object.__new__(cls)
3975 obj.l = 0
3976 obj.r = 0
3977 return obj
3978
3979 def test_dunder_new() -> None:
3980 add_instance: Any = Add(1, 5)
3981 assert type(add_instance) == Add
3982 assert add_instance.l == 1
3983 assert add_instance.r == 5
3984
3985 # TODO: explicit types should not be needed but mypy does not use
3986 # the return type of __new__ which makes mypyc add casts to Add.
3987 right_int: Any = Add(0, 5)
3988 assert type(right_int) == int
3989 assert right_int == 5
3990
3991 left_int: Any = Add(1, 0)
3992 assert type(left_int) == int
3993 assert left_int == 1
3994
3995 with assertRaises(RuntimeError, "Invalid value!"):
3996 _ = RaisesException(0)
3997
3998 not_raised = RaisesException(1)
3999 assert not_raised.val == 1
4000
4001 with assertRaises(TypeError, "object.__new__(str) is not safe, use str.__new__()"):
4002 _ = ClsArgNotPassed()
4003
4004 skip = SkipsBase.__new__(SkipsBase)
4005 assert type(skip) == SkipsBase
4006 assert skip.l == 0
4007 assert skip.r == 0
4008
4009 [case testObjectDunderNewInInterpreted]
4010 from __future__ import annotations
4011 from typing import Any, Union
4012
4013 class Add:
4014 l: IntLike
4015 r: IntLike
4016
4017 def __new__(cls, l: IntLike, r: IntLike) -> Any:
4018 print(f'running __new__ with {l} and {r}')
4019
4020 return (
4021 l if r == 0 else
4022 r if l == 0 else
4023 object.__new__(cls)
4024 )
4025
4026 def __init__(self, l: IntLike, r: IntLike):
4027 self.l = l
4028 self.r = r
4029
4030 def __repr__(self) -> str:
4031 return f'({self.l} + {self.r})'
4032
4033 IntLike = Union[int, Add]
4034
4035 class RaisesException:
4036 def __new__(cls, val: int) -> RaisesException:
4037 if val == 0:
4038 raise RuntimeError("Invalid value!")
4039 return object.__new__(cls)
4040
4041 def __init__(self, val: int) -> None:
4042 self.val = val
4043
4044 class ClsArgNotPassed:
4045 def __new__(cls) -> Any:
4046 return object.__new__(str)
4047
4048 class SkipsBase(Add):
4049 def __new__(cls) -> Any:
4050 obj = object.__new__(cls)
4051 obj.l = 0
4052 obj.r = 0
4053 return obj
4054
4055 [file driver.py]
4056 from native import Add, ClsArgNotPassed, RaisesException, SkipsBase
4057
4058 from testutil import assertRaises
4059
4060 print(f'{Add(1, 5)=}')
4061 print(f'{Add(0, 5)=}')
4062 print(f'{Add(1, 0)=}')
4063
4064 with assertRaises(RuntimeError, "Invalid value!"):
4065 raised = RaisesException(0)
4066
4067 not_raised = RaisesException(1)
4068 assert not_raised.val == 1
4069
4070 with assertRaises(TypeError, "object.__new__(str) is not safe, use str.__new__()"):
4071 str_as_cls = ClsArgNotPassed()
4072
4073 skip = SkipsBase.__new__(SkipsBase)
4074 assert type(skip) == SkipsBase
4075 assert skip.l == 0
4076 assert skip.r == 0
4077
4078 [out]
4079 running __new__ with 1 and 5
4080 Add(1, 5)=(1 + 5)
4081 running __new__ with 0 and 5
4082 Add(0, 5)=5
4083 running __new__ with 1 and 0
4084 Add(1, 0)=1
4085
4086 [case testInheritedDunderNew]
4087 from __future__ import annotations
4088 from mypy_extensions import mypyc_attr
4089 from testutil import assertRaises
4090 from typing_extensions import Self
4091
4092 from m import interpreted_subclass
4093
4094 @mypyc_attr(allow_interpreted_subclasses=True)
4095 class Base:
4096 val: int
4097
4098 def __new__(cls, val: int) -> Self:
4099 obj = super().__new__(cls)
4100 obj.val = val + 1
4101 return obj
4102
4103 def __init__(self, val: int) -> None:
4104 self.init_val = val
4105
4106 def method(self) -> int:
4107 raise NotImplementedError
4108
4109 class Sub(Base):
4110
4111 def __new__(cls, val: int) -> Self:
4112 return super().__new__(cls, val + 1)
4113
4114 def __init__(self, val: int) -> None:
4115 super().__init__(val)
4116 self.init_val = self.init_val * 2
4117
4118 def method(self) -> int:
4119 return 0
4120
4121 class SubWithoutNew(Base):
4122 sub_only_str = ""
4123 sub_only_int: int
4124
4125 def __init__(self, val: int) -> None:
4126 super().__init__(val)
4127 self.init_val = self.init_val * 2
4128
4129 def method(self) -> int:
4130 return 1
4131
4132 class BaseWithoutInterpretedSubclasses:
4133 val: int
4134
4135 def __new__(cls, val: int) -> Self:
4136 obj = super().__new__(cls)
4137 obj.val = val + 1
4138 return obj
4139
4140 def __init__(self, val: int) -> None:
4141 self.init_val = val
4142
4143 def method(self) -> int:
4144 raise NotImplementedError
4145
4146 class SubNoInterpreted(BaseWithoutInterpretedSubclasses):
4147 def __new__(cls, val: int) -> Self:
4148 return super().__new__(cls, val + 1)
4149
4150 def __init__(self, val: int) -> None:
4151 super().__init__(val)
4152 self.init_val = self.init_val * 2
4153
4154 def method(self) -> int:
4155 return 0
4156
4157 class SubNoInterpretedWithoutNew(BaseWithoutInterpretedSubclasses):
4158 def __init__(self, val: int) -> None:
4159 super().__init__(val)
4160 self.init_val = self.init_val * 2
4161
4162 def method(self) -> int:
4163 return 1
4164
4165 def test_inherited_dunder_new() -> None:
4166 b = Base(42)
4167 assert type(b) == Base
4168 assert b.val == 43
4169 assert b.init_val == 42
4170 with assertRaises(NotImplementedError):
4171 b.method()
4172
4173 s = Sub(42)
4174 assert type(s) == Sub
4175 assert s.val == 44
4176 assert s.init_val == 84
4177 assert s.method() == 0
4178
4179 s2 = SubWithoutNew(42)
4180 assert type(s2) == SubWithoutNew
4181 assert s2.val == 43
4182 assert s2.init_val == 84
4183 assert s2.method() == 1
4184 assert s2.sub_only_str == ""
4185 with assertRaises(AttributeError):
4186 s2.sub_only_int
4187 s2.sub_only_int = 11
4188 assert s2.sub_only_int == 11
4189
4190 def test_inherited_dunder_new_without_interpreted_subclasses() -> None:
4191 b = BaseWithoutInterpretedSubclasses(42)
4192 assert type(b) == BaseWithoutInterpretedSubclasses
4193 assert b.val == 43
4194 assert b.init_val == 42
4195 with assertRaises(NotImplementedError):
4196 b.method()
4197
4198 s = SubNoInterpreted(42)
4199 assert type(s) == SubNoInterpreted
4200 assert s.val == 44
4201 assert s.init_val == 84
4202 assert s.method() == 0
4203
4204 s2 = SubNoInterpretedWithoutNew(42)
4205 assert type(s2) == SubNoInterpretedWithoutNew
4206 assert s2.val == 43
4207 assert s2.init_val == 84
4208 assert s2.method() == 1
4209
4210 def test_interpreted_subclass() -> None:
4211 interpreted_subclass(Base)
4212
4213 [file m.py]
4214 from __future__ import annotations
4215 from testutil import assertRaises
4216 from typing_extensions import Self
4217
4218 def interpreted_subclass(base) -> None:
4219 b = base(42)
4220 assert type(b) == base
4221 assert b.val == 43
4222 assert b.init_val == 42
4223 with assertRaises(NotImplementedError):
4224 b.method()
4225
4226 class InterpretedSub(base):
4227 def __new__(cls, val: int) -> Self:
4228 return super().__new__(cls, val + 1)
4229
4230 def __init__(self, val: int) -> None:
4231 super().__init__(val)
4232 self.init_val : int = self.init_val * 2
4233
4234 def method(self) -> int:
4235 return 3
4236
4237 s = InterpretedSub(42)
4238 assert type(s) == InterpretedSub
4239 assert s.val == 44
4240 assert s.init_val == 84
4241 assert s.method() == 3
4242
4243 class InterpretedSubWithoutNew(base):
4244 sub_only_str = ""
4245 sub_only_int: int
4246
4247 def __init__(self, val: int) -> None:
4248 super().__init__(val)
4249 self.init_val : int = self.init_val * 2
4250
4251 def method(self) -> int:
4252 return 4
4253
4254 s2 = InterpretedSubWithoutNew(42)
4255 assert type(s2) == InterpretedSubWithoutNew
4256 assert s2.val == 43
4257 assert s2.init_val == 84
4258 assert s2.method() == 4
4259 assert s2.sub_only_str == ""
4260 with assertRaises(AttributeError):
4261 s2.sub_only_int
4262 s2.sub_only_int = 11
4263 assert s2.sub_only_int == 11
4264
4265 [typing fixtures/typing-full.pyi]
4266
4267 [case testDunderNewInitArgMismatch]
4268 from __future__ import annotations
4269 from testutil import assertRaises
4270
4271 class Test0:
4272 @classmethod
4273 def __new__(cls, val: int = 42) -> Test0:
4274 obj = super().__new__(cls)
4275 obj.val = val
4276 return obj
4277
4278 def __init__(self) -> None:
4279 self.val = 0
4280
4281 class Test1:
4282 def __new__(cls, val: int) -> Test1:
4283 obj = super().__new__(cls)
4284 obj.val = val
4285 return obj
4286
4287 def __init__(self) -> None:
4288 self.val = 0
4289
4290 class Test2:
4291 def __new__(cls) -> Test2:
4292 obj = super().__new__(cls)
4293 return obj
4294
4295 def __init__(self, val: int) -> None:
4296 self.val = val
4297
4298 def test_arg_mismatch() -> None:
4299 t0 = Test0()
4300 assert t0.val == 0
4301 t0 = Test0.__new__(1)
4302 assert t0.val == 1
4303 with assertRaises(TypeError, "__new__() missing required argument 'val'"):
4304 t1 = Test1()
4305 t1 = Test1.__new__(Test1, 2)
4306 assert t1.val == 2
4307 with assertRaises(TypeError, "__new__() takes at most 0 arguments"):
4308 t2 = Test2(42)
4309 t2 = Test2.__new__(Test2)
4310 with assertRaises(AttributeError, "attribute 'val' of 'Test2' undefined"):
4311 print(t2.val)
4312
4313 [case testDunderNewInitArgMismatchInInterpreted]
4314 from __future__ import annotations
4315
4316 class Test0:
4317 # TODO: It should be possible to annotate '@classmethod' here
4318 # but when it's added calling __new__ in interpreted code
4319 # without the explicit type param results in a TypeError.
4320 def __new__(cls, val: int = 42) -> Test0:
4321 obj = super().__new__(cls)
4322 obj.val = val
4323 return obj
4324
4325 def __init__(self) -> None:
4326 self.val = 0
4327
4328 class Test1:
4329 def __new__(cls, val: int) -> Test1:
4330 obj = super().__new__(cls)
4331 obj.val = val
4332 return obj
4333
4334 def __init__(self) -> None:
4335 self.val = 0
4336
4337 class Test2:
4338 def __new__(cls) -> Test2:
4339 obj = super().__new__(cls)
4340 return obj
4341
4342 def __init__(self, val: int) -> None:
4343 self.val = val
4344
4345 [file driver.py]
4346 from native import Test0, Test1, Test2
4347 from testutil import assertRaises
4348
4349 t0 = Test0()
4350 assert t0.val == 0
4351 t0 = Test0.__new__(Test0, 1)
4352 assert t0.val == 1
4353 with assertRaises(TypeError, "__new__() missing required argument 'val'"):
4354 t1 = Test1()
4355 t1 = Test1.__new__(Test1, 2)
4356 assert t1.val == 2
4357 with assertRaises(TypeError, "__new__() takes at most 0 arguments"):
4358 t2 = Test2(42)
4359 t2 = Test2.__new__(Test2)
4360 with assertRaises(AttributeError, "attribute 'val' of 'Test2' undefined"):
4361 print(t2.val)
4362
4363 [case testDunderNewAttributeAccess]
4364 from __future__ import annotations
4365
4366 from mypy_extensions import u8
4367 from testutil import assertRaises
4368
4369 class Test:
4370 native: int
4371 generic: object
4372 bitfield: u8
4373 default: int = 5
4374
4375 def __new__(cls, native: int, generic: object, bitfield: u8) -> Test:
4376 obj = super().__new__(cls)
4377
4378 with assertRaises(AttributeError, "attribute 'native' of 'Test' undefined"):
4379 print(obj.native)
4380 with assertRaises(AttributeError, "attribute 'generic' of 'Test' undefined"):
4381 print(obj.generic)
4382 with assertRaises(AttributeError, "attribute 'bitfield' of 'Test' undefined"):
4383 print(obj.bitfield)
4384
4385 obj.native = native
4386 obj.generic = generic
4387 obj.bitfield = bitfield
4388
4389 obj.native = obj.native + 1
4390 obj.generic = obj.generic.__str__()
4391 obj.bitfield = obj.bitfield & 0x0F
4392 obj.default = obj.default * 2
4393 return obj
4394
4395 def test_attribute_access() -> None:
4396 t = Test(42, {}, 0xCC)
4397 assert t.native == 43
4398 assert t.generic == "{}"
4399 assert t.bitfield == 0x0C
4400 assert t.default == 10
4401
4402 [case testDunderNewAttributeAccessInInterpreted]
4403 from __future__ import annotations
4404
4405 from mypy_extensions import u8
4406 from testutil import assertRaises
4407
4408 class Test:
4409 native: int
4410 generic: object
4411 bitfield: u8
4412 default: int = 5
4413
4414 def __new__(cls, native: int, generic: object, bitfield: u8) -> Test:
4415 obj = super().__new__(cls)
4416
4417 with assertRaises(AttributeError, "attribute 'native' of 'Test' undefined"):
4418 print(obj.native)
4419 with assertRaises(AttributeError, "attribute 'generic' of 'Test' undefined"):
4420 print(obj.generic)
4421 with assertRaises(AttributeError, "attribute 'bitfield' of 'Test' undefined"):
4422 print(obj.bitfield)
4423
4424 obj.native = native
4425 obj.generic = generic
4426 obj.bitfield = bitfield
4427
4428 obj.native = obj.native + 1
4429 obj.generic = obj.generic.__str__()
4430 obj.bitfield = obj.bitfield & 0x0F
4431 obj.default = obj.default * 2
4432 return obj
4433
4434 [file driver.py]
4435 from native import Test
4436
4437 t = Test(42, {}, 0xCC)
4438 assert t.native == 43
4439 assert t.generic == "{}"
4440 assert t.bitfield == 0x0C
4441 assert t.default == 10
4442
4443 [case testUntransformedDunderNewCalls]
4444 from testutil import assertRaises
4445 from typing import Any
4446
4447 class TestStrCls:
4448 def __new__(cls):
4449 return str.__new__(cls)
4450
4451 @classmethod
4452 def factory(cls):
4453 return str.__new__(cls)
4454
4455 class TestStrStr:
4456 def __new__(cls):
4457 return str.__new__(str)
4458
4459 @classmethod
4460 def factory(cls):
4461 return str.__new__(str)
4462
4463 class TestStrInt:
4464 def __new__(cls):
4465 return str.__new__(int)
4466
4467 @classmethod
4468 def factory(cls):
4469 return str.__new__(int)
4470
4471 def test_untransformed_dunder_new() -> None:
4472 with assertRaises(TypeError, "str.__new__(TestStrCls): TestStrCls is not a subtype of str"):
4473 i = TestStrCls()
4474
4475 j: Any = TestStrStr()
4476 assert j == ""
4477
4478 with assertRaises(TypeError, "str.__new__(int): int is not a subtype of str"):
4479 k = TestStrInt()
4480
4481 with assertRaises(TypeError, "str.__new__(TestStrCls): TestStrCls is not a subtype of str"):
4482 i = TestStrCls.factory()
4483
4484 j = TestStrStr.factory()
4485 assert j == ""
4486
4487 with assertRaises(TypeError, "str.__new__(int): int is not a subtype of str"):
4488 k = TestStrInt.factory()
4489
4490 [case testPerTypeFreeList]
4491 from __future__ import annotations
4492
4493 from mypy_extensions import mypyc_attr
4494
4495 a: list[int] = []
4496
4497 @mypyc_attr(free_list_len=1)
4498 class Foo:
4499 def __init__(self, x: int) -> None:
4500 self.x = x
4501 a.append(x)
4502
4503 def test_alloc() -> None:
4504 x: Foo | None
4505 y: Foo | None
4506
4507 x = Foo(1)
4508 assert x.x == 1
4509 x = None
4510
4511 x = Foo(2)
4512 assert x.x == 2
4513 y = Foo(3)
4514 assert x.x == 2
4515 assert y.x == 3
4516 x = None
4517 y = None
4518 assert a == [1, 2, 3]
4519
4520 x = Foo(4)
4521 assert x.x == 4
4522 y = Foo(5)
4523 assert x.x == 4
4524 assert y.x == 5
4525
4526 @mypyc_attr(free_list_len=1)
4527 class Base:
4528 def __init__(self, x: str) -> None:
4529 self.x = x
4530
4531 class Deriv(Base):
4532 def __init__(self, x: str, y: str) -> None:
4533 super().__init__(x)
4534 self.y = y
4535
4536 @mypyc_attr(free_list_len=1)
4537 class Deriv2(Base):
4538 def __init__(self, x: str, y: str) -> None:
4539 super().__init__(x)
4540 self.y = y
4541
4542 def test_inheritance() -> None:
4543 x: Base | None
4544 y: Base | None
4545 x = Base('x' + str())
4546 y = Base('y' + str())
4547 y = None
4548 d = Deriv('a' + str(), 'b' + str())
4549 assert type(d) is Deriv
4550 assert d.x == 'a'
4551 assert d.y == 'b'
4552 assert x.x == 'x'
4553 y = Base('z' + str())
4554 assert d.x == 'a'
4555 assert d.y == 'b'
4556 assert y.x == 'z'
4557 x = None
4558 y = None
4559
4560 def test_inheritance_2() -> None:
4561 x: Base | None
4562 y: Base | None
4563 d: Deriv2 | None
4564 x = Base('x' + str())
4565 y = Base('y' + str())
4566 y = None
4567 d = Deriv2('a' + str(), 'b' + str())
4568 assert type(d) is Deriv2
4569 assert d.x == 'a'
4570 assert d.y == 'b'
4571 assert x.x == 'x'
4572 d = None
4573 d = Deriv2('c' + str(), 'd' + str())
4574 assert type(d) is Deriv2
4575 assert d.x == 'c'
4576 assert d.y == 'd'
4577 assert x.x == 'x'
4578 y = Base('z' + str())
4579 assert type(y) is Base
4580 assert d.x == 'c'
4581 assert d.y == 'd'
4582 assert y.x == 'z'
4583 x = None
4584 y = None
4585 d = None
4586
4587 [case testDunderGetAttr]
4588 from mypy_extensions import mypyc_attr
4589 from typing import ClassVar
4590
4591 class GetAttr:
4592 class_var = "x"
4593
4594 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4595 self.extra_attrs = extra_attrs
4596 self.regular_attr = regular_attr
4597
4598 def __getattr__(self, attr: str) -> object:
4599 return self.extra_attrs.get(attr)
4600
4601 class GetAttrDefault:
4602 class_var: ClassVar[str] = "x"
4603
4604 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4605 self.extra_attrs = extra_attrs
4606 self.regular_attr = regular_attr
4607
4608 def __getattr__(self, attr: str, default: int = 8, mult: int = 1) -> object:
4609 return self.extra_attrs.get(attr, default * mult)
4610
4611 class GetAttrInherited(GetAttr):
4612 subclass_var = "y"
4613
4614 def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):
4615 super().__init__(extra_attrs, regular_attr)
4616 self.sub_attr = sub_attr
4617
4618 class GetAttrOverridden(GetAttr):
4619 subclass_var: ClassVar[str] = "y"
4620
4621 def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):
4622 super().__init__(extra_attrs, regular_attr)
4623 self.sub_attr = sub_attr
4624
4625 def __getattr__(self, attr: str) -> str:
4626 return attr
4627
4628 @mypyc_attr(native_class=False)
4629 class GetAttrNonNative:
4630 class_var = "x"
4631
4632 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4633 self.extra_attrs = extra_attrs
4634 self.regular_attr = regular_attr
4635
4636 def __getattr__(self, attr: str) -> object:
4637 return self.extra_attrs.get(attr)
4638
4639 def test_getattr() -> None:
4640 i = GetAttr({"one": 1, "two": "two", "three": 3.14}, 42)
4641 assert i.__getattr__("one") == 1
4642 assert i.__getattr__("regular_attr") == None
4643 assert i.__getattr__("class_var") == None
4644 assert i.__getattr__("four") == None
4645
4646 assert getattr(i, "two") == "two"
4647 assert getattr(i, "regular_attr") == 42
4648 assert getattr(i, "class_var") == "x"
4649 assert getattr(i, "four") == None
4650
4651 assert i.three == 3.14
4652 assert i.regular_attr == 42
4653 assert i.class_var == "x"
4654 assert i.four == None
4655
4656 assert i.__class__ == GetAttr
4657
4658 i.extra_attrs["regular_attr"] = (4, 4, 4)
4659 assert i.__getattr__("regular_attr") == (4, 4, 4)
4660 assert getattr(i, "regular_attr") == 42
4661 assert i.regular_attr == 42
4662
4663 def test_getattr_default() -> None:
4664 i = GetAttrDefault({"one": 1, "two": "two", "three": 3.14}, 42)
4665 assert i.__getattr__("one") == 1
4666 assert i.__getattr__("regular_attr") == 8
4667 assert i.__getattr__("class_var") == 8
4668 assert i.__getattr__("four", 4, 3) == 12
4669
4670 assert getattr(i, "two") == "two"
4671 assert getattr(i, "regular_attr") == 42
4672 assert getattr(i, "class_var") == "x"
4673 assert getattr(i, "four") == 8
4674
4675 assert i.three == 3.14
4676 assert i.regular_attr == 42
4677 assert i.class_var == "x"
4678 assert i.four == 8
4679
4680 assert i.__class__ == GetAttrDefault
4681
4682 i.extra_attrs["class_var"] = (4, 4, 4)
4683 assert i.__getattr__("class_var") == (4, 4, 4)
4684 assert getattr(i, "class_var") == "x"
4685 assert i.class_var == "x"
4686
4687 def test_getattr_inherited() -> None:
4688 i = GetAttrInherited({"one": 1, "two": "two", "three": 3.14}, 42, 24)
4689 assert i.__getattr__("one") == 1
4690 assert i.__getattr__("regular_attr") == None
4691 assert i.__getattr__("sub_attr") == None
4692 assert i.__getattr__("class_var") == None
4693 assert i.__getattr__("subclass_var") == None
4694 assert i.__getattr__("four") == None
4695
4696 assert getattr(i, "two") == "two"
4697 assert getattr(i, "regular_attr") == 42
4698 assert getattr(i, "sub_attr") == 24
4699 assert getattr(i, "class_var") == "x"
4700 assert getattr(i, "subclass_var") == "y"
4701 assert getattr(i, "four") == None
4702
4703 assert i.three == 3.14
4704 assert i.regular_attr == 42
4705 assert i.sub_attr == 24
4706 assert i.class_var == "x"
4707 assert i.subclass_var == "y"
4708 assert i.four == None
4709
4710 assert i.__class__ == GetAttrInherited
4711
4712 i.extra_attrs["sub_attr"] = (4, 4, 4)
4713 assert i.__getattr__("sub_attr") == (4, 4, 4)
4714 assert getattr(i, "sub_attr") == 24
4715 assert i.sub_attr == 24
4716
4717 base_ref: GetAttr = i
4718 assert getattr(base_ref, "sub_attr") == 24
4719 assert base_ref.sub_attr == 24
4720
4721 assert getattr(base_ref, "subclass_var") == "y"
4722 assert base_ref.subclass_var == "y"
4723
4724 assert getattr(base_ref, "new") == None
4725 assert base_ref.new == None
4726
4727 assert base_ref.__class__ == GetAttrInherited
4728
4729
4730 def test_getattr_overridden() -> None:
4731 i = GetAttrOverridden({"one": 1, "two": "two", "three": 3.14}, 42, 24)
4732 assert i.__getattr__("one") == "one"
4733 assert i.__getattr__("regular_attr") == "regular_attr"
4734 assert i.__getattr__("sub_attr") == "sub_attr"
4735 assert i.__getattr__("class_var") == "class_var"
4736 assert i.__getattr__("subclass_var") == "subclass_var"
4737 assert i.__getattr__("four") == "four"
4738
4739 assert getattr(i, "two") == "two"
4740 assert getattr(i, "regular_attr") == 42
4741 assert getattr(i, "sub_attr") == 24
4742 assert getattr(i, "class_var") == "x"
4743 assert getattr(i, "subclass_var") == "y"
4744 assert getattr(i, "four") == "four"
4745
4746 assert i.three == "three"
4747 assert i.regular_attr == 42
4748 assert i.sub_attr == 24
4749 assert i.class_var == "x"
4750 assert i.subclass_var == "y"
4751 assert i.four == "four"
4752
4753 assert i.__class__ == GetAttrOverridden
4754
4755 i.extra_attrs["subclass_var"] = (4, 4, 4)
4756 assert i.__getattr__("subclass_var") == "subclass_var"
4757 assert getattr(i, "subclass_var") == "y"
4758 assert i.subclass_var == "y"
4759
4760 base_ref: GetAttr = i
4761 assert getattr(base_ref, "sub_attr") == 24
4762 assert base_ref.sub_attr == 24
4763
4764 assert getattr(base_ref, "subclass_var") == "y"
4765 assert base_ref.subclass_var == "y"
4766
4767 assert getattr(base_ref, "new") == "new"
4768 assert base_ref.new == "new"
4769
4770 assert base_ref.__class__ == GetAttrOverridden
4771
4772 def test_getattr_nonnative() -> None:
4773 i = GetAttr({"one": 1, "two": "two", "three": 3.14}, 42)
4774 assert i.__getattr__("one") == 1
4775 assert i.__getattr__("regular_attr") == None
4776 assert i.__getattr__("class_var") == None
4777 assert i.__getattr__("four") == None
4778
4779 assert getattr(i, "two") == "two"
4780 assert getattr(i, "regular_attr") == 42
4781 assert getattr(i, "class_var") == "x"
4782 assert getattr(i, "four") == None
4783
4784 assert i.three == 3.14
4785 assert i.regular_attr == 42
4786 assert i.class_var == "x"
4787 assert i.four == None
4788
4789 assert i.__class__ == GetAttr
4790
4791 i.extra_attrs["regular_attr"] = (4, 4, 4)
4792 assert i.__getattr__("regular_attr") == (4, 4, 4)
4793 assert getattr(i, "regular_attr") == 42
4794 assert i.regular_attr == 42
4795
4796 [typing fixtures/typing-full.pyi]
4797
4798 [case testDunderGetAttrInterpreted]
4799 from mypy_extensions import mypyc_attr
4800 from typing import ClassVar
4801
4802 class GetAttr:
4803 class_var = "x"
4804
4805 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4806 self.extra_attrs = extra_attrs
4807 self.regular_attr = regular_attr
4808
4809 def __getattr__(self, attr: str) -> object:
4810 return self.extra_attrs.get(attr)
4811
4812 class GetAttrDefault:
4813 class_var: ClassVar[str] = "x"
4814
4815 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4816 self.extra_attrs = extra_attrs
4817 self.regular_attr = regular_attr
4818
4819 def __getattr__(self, attr: str, default: int = 8, mult: int = 1) -> object:
4820 return self.extra_attrs.get(attr, default * mult)
4821
4822 class GetAttrInherited(GetAttr):
4823 subclass_var = "y"
4824
4825 def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):
4826 super().__init__(extra_attrs, regular_attr)
4827 self.sub_attr = sub_attr
4828
4829 class GetAttrOverridden(GetAttr):
4830 subclass_var: ClassVar[str] = "y"
4831
4832 def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):
4833 super().__init__(extra_attrs, regular_attr)
4834 self.sub_attr = sub_attr
4835
4836 def __getattr__(self, attr: str) -> str:
4837 return attr
4838
4839 @mypyc_attr(native_class=False)
4840 class GetAttrNonNative:
4841 class_var = "x"
4842
4843 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4844 self.extra_attrs = extra_attrs
4845 self.regular_attr = regular_attr
4846
4847 def __getattr__(self, attr: str) -> object:
4848 return self.extra_attrs.get(attr)
4849
4850 [file driver.py]
4851 from native import GetAttr, GetAttrDefault, GetAttrInherited, GetAttrOverridden, GetAttrNonNative
4852
4853 def test_getattr() -> None:
4854 i = GetAttr({"one": 1, "two": "two", "three": 3.14}, 42)
4855 assert i.__getattr__("one") == 1
4856 assert i.__getattr__("regular_attr") == None
4857 assert i.__getattr__("class_var") == None
4858 assert i.__getattr__("four") == None
4859
4860 assert getattr(i, "two") == "two"
4861 assert getattr(i, "regular_attr") == 42
4862 assert getattr(i, "class_var") == "x"
4863 assert getattr(i, "four") == None
4864
4865 assert i.three == 3.14
4866 assert i.regular_attr == 42
4867 assert i.class_var == "x"
4868 assert i.four == None
4869
4870 assert i.__class__ == GetAttr
4871
4872 i.extra_attrs["regular_attr"] = (4, 4, 4)
4873 assert i.__getattr__("regular_attr") == (4, 4, 4)
4874 assert getattr(i, "regular_attr") == 42
4875 assert i.regular_attr == 42
4876
4877 def test_getattr_default() -> None:
4878 i = GetAttrDefault({"one": 1, "two": "two", "three": 3.14}, 42)
4879 assert i.__getattr__("one") == 1
4880 assert i.__getattr__("regular_attr") == 8
4881 assert i.__getattr__("class_var") == 8
4882 assert i.__getattr__("four", 4, 3) == 12
4883
4884 assert getattr(i, "two") == "two"
4885 assert getattr(i, "regular_attr") == 42
4886 assert getattr(i, "class_var") == "x"
4887 assert getattr(i, "four") == 8
4888
4889 assert i.three == 3.14
4890 assert i.regular_attr == 42
4891 assert i.class_var == "x"
4892 assert i.four == 8
4893
4894 assert i.__class__ == GetAttrDefault
4895
4896 i.extra_attrs["class_var"] = (4, 4, 4)
4897 assert i.__getattr__("class_var") == (4, 4, 4)
4898 assert getattr(i, "class_var") == "x"
4899 assert i.class_var == "x"
4900
4901 def test_getattr_inherited() -> None:
4902 i = GetAttrInherited({"one": 1, "two": "two", "three": 3.14}, 42, 24)
4903 assert i.__getattr__("one") == 1
4904 assert i.__getattr__("regular_attr") == None
4905 assert i.__getattr__("sub_attr") == None
4906 assert i.__getattr__("class_var") == None
4907 assert i.__getattr__("subclass_var") == None
4908 assert i.__getattr__("four") == None
4909
4910 assert getattr(i, "two") == "two"
4911 assert getattr(i, "regular_attr") == 42
4912 assert getattr(i, "sub_attr") == 24
4913 assert getattr(i, "class_var") == "x"
4914 assert getattr(i, "subclass_var") == "y"
4915 assert getattr(i, "four") == None
4916
4917 assert i.three == 3.14
4918 assert i.regular_attr == 42
4919 assert i.sub_attr == 24
4920 assert i.class_var == "x"
4921 assert i.subclass_var == "y"
4922 assert i.four == None
4923
4924 assert i.__class__ == GetAttrInherited
4925
4926 i.extra_attrs["sub_attr"] = (4, 4, 4)
4927 assert i.__getattr__("sub_attr") == (4, 4, 4)
4928 assert getattr(i, "sub_attr") == 24
4929 assert i.sub_attr == 24
4930
4931 base_ref: GetAttr = i
4932 assert getattr(base_ref, "sub_attr") == 24
4933 assert base_ref.sub_attr == 24
4934
4935 assert getattr(base_ref, "subclass_var") == "y"
4936 assert base_ref.subclass_var == "y"
4937
4938 assert getattr(base_ref, "new") == None
4939 assert base_ref.new == None
4940
4941 assert base_ref.__class__ == GetAttrInherited
4942
4943
4944 def test_getattr_overridden() -> None:
4945 i = GetAttrOverridden({"one": 1, "two": "two", "three": 3.14}, 42, 24)
4946 assert i.__getattr__("one") == "one"
4947 assert i.__getattr__("regular_attr") == "regular_attr"
4948 assert i.__getattr__("sub_attr") == "sub_attr"
4949 assert i.__getattr__("class_var") == "class_var"
4950 assert i.__getattr__("subclass_var") == "subclass_var"
4951 assert i.__getattr__("four") == "four"
4952
4953 assert getattr(i, "two") == "two"
4954 assert getattr(i, "regular_attr") == 42
4955 assert getattr(i, "sub_attr") == 24
4956 assert getattr(i, "class_var") == "x"
4957 assert getattr(i, "subclass_var") == "y"
4958 assert getattr(i, "four") == "four"
4959
4960 assert i.three == "three"
4961 assert i.regular_attr == 42
4962 assert i.sub_attr == 24
4963 assert i.class_var == "x"
4964 assert i.subclass_var == "y"
4965 assert i.four == "four"
4966
4967 assert i.__class__ == GetAttrOverridden
4968
4969 i.extra_attrs["subclass_var"] = (4, 4, 4)
4970 assert i.__getattr__("subclass_var") == "subclass_var"
4971 assert getattr(i, "subclass_var") == "y"
4972 assert i.subclass_var == "y"
4973
4974 base_ref: GetAttr = i
4975 assert getattr(base_ref, "sub_attr") == 24
4976 assert base_ref.sub_attr == 24
4977
4978 assert getattr(base_ref, "subclass_var") == "y"
4979 assert base_ref.subclass_var == "y"
4980
4981 assert getattr(base_ref, "new") == "new"
4982 assert base_ref.new == "new"
4983
4984 assert base_ref.__class__ == GetAttrOverridden
4985
4986 def test_getattr_nonnative() -> None:
4987 i = GetAttr({"one": 1, "two": "two", "three": 3.14}, 42)
4988 assert i.__getattr__("one") == 1
4989 assert i.__getattr__("regular_attr") == None
4990 assert i.__getattr__("class_var") == None
4991 assert i.__getattr__("four") == None
4992
4993 assert getattr(i, "two") == "two"
4994 assert getattr(i, "regular_attr") == 42
4995 assert getattr(i, "class_var") == "x"
4996 assert getattr(i, "four") == None
4997
4998 assert i.three == 3.14
4999 assert i.regular_attr == 42
5000 assert i.class_var == "x"
5001 assert i.four == None
5002
5003 assert i.__class__ == GetAttr
5004
5005 i.extra_attrs["regular_attr"] = (4, 4, 4)
5006 assert i.__getattr__("regular_attr") == (4, 4, 4)
5007 assert getattr(i, "regular_attr") == 42
5008 assert i.regular_attr == 42
5009
5010 test_getattr()
5011 test_getattr_default()
5012 test_getattr_inherited()
5013 test_getattr_overridden()
5014 test_getattr_nonnative()
5015
5016 [typing fixtures/typing-full.pyi]
5017
5018 [case testDunderSetAttr]
5019 from mypy_extensions import mypyc_attr
5020 from testutil import assertRaises
5021 from typing import ClassVar
5022
5023 class SetAttr:
5024 _attributes: dict[str, object]
5025 regular_attr: int
5026 class_var: ClassVar[str] = "x"
5027 const: int = 42
5028
5029 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
5030 super().__setattr__("_attributes", extra_attrs)
5031 super().__setattr__("regular_attr", regular_attr)
5032
5033 def __setattr__(self, key: str, val: object) -> None:
5034 if key == "regular_attr":
5035 super().__setattr__("regular_attr", val)
5036 elif key == "class_var" or key == "const":
5037 raise AttributeError()
5038 else:
5039 self._attributes[key] = val
5040
5041 def __getattr__(self, key: str) -> object:
5042 return self._attributes.get(key)
5043
5044 class SetAttrInherited(SetAttr):
5045 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
5046 super().__init__(regular_attr, extra_attrs)
5047
5048 class SetAttrOverridden(SetAttr):
5049 sub_attr: int
5050 subclass_var: ClassVar[str] = "y"
5051
5052 def __init__(self, regular_attr: int, sub_attr: int, extra_attrs: dict[str, object]) -> None:
5053 super().__init__(regular_attr, extra_attrs)
5054 object.__setattr__(self, "sub_attr", sub_attr)
5055
5056 def __setattr__(self, key: str, val: object) -> None:
5057 if key == "sub_attr":
5058 object.__setattr__(self, "sub_attr", val)
5059 elif key == "subclass_var":
5060 raise AttributeError()
5061 else:
5062 super().__setattr__(key, val)
5063
5064 def __delattr__(self, key: str) -> None:
5065 del self._attributes[key]
5066
5067 @mypyc_attr(native_class=False)
5068 class SetAttrNonNative:
5069 _attributes: dict[str, object]
5070 regular_attr: int
5071 class_var: ClassVar[str] = "x"
5072 const: int = 42
5073
5074 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
5075 super().__setattr__("_attributes", extra_attrs)
5076 super().__setattr__("regular_attr", regular_attr)
5077
5078 def __setattr__(self, key: str, val: object) -> None:
5079 if key == "regular_attr":
5080 super().__setattr__("regular_attr", val)
5081 elif key == "class_var" or key == "const":
5082 raise AttributeError()
5083 else:
5084 self._attributes[key] = val
5085
5086 def __getattr__(self, key: str) -> object:
5087 return self._attributes.get(key)
5088
5089 class NoSetAttr:
5090 def __init__(self, attr: int) -> None:
5091 self.attr = attr
5092
5093 def object_setattr(self, attr: str, val: object) -> None:
5094 object.__setattr__(self, attr, val)
5095
5096 def super_setattr(self, attr: str, val: object) -> None:
5097 super().__setattr__(attr, val)
5098
5099 @mypyc_attr(native_class=False)
5100 class NoSetAttrNonNative:
5101 def __init__(self, attr: int) -> None:
5102 self.attr = attr
5103
5104 def object_setattr(self, attr: str, val: object) -> None:
5105 object.__setattr__(self, attr, val)
5106
5107 def super_setattr(self, attr: str, val: object) -> None:
5108 super().__setattr__(attr, val)
5109
5110 def __getattr__(self, attr: str) -> object:
5111 pass
5112
5113 def test_setattr() -> None:
5114 i = SetAttr(99, {"one": 1})
5115 assert i.class_var == "x"
5116 assert i.regular_attr == 99
5117 assert i.one == 1
5118 assert i.two == None
5119 assert i.const == 42
5120 i = i
5121
5122 i.__setattr__("two", "2")
5123 assert i.two == "2"
5124 i.__setattr__("regular_attr", 101)
5125 assert i.regular_attr == 101
5126 with assertRaises(AttributeError):
5127 i.__setattr__("class_var", "y")
5128 with assertRaises(AttributeError):
5129 i.__setattr__("const", 43)
5130
5131 setattr(i, "three", (3,3,3))
5132 assert i.three == (3,3,3)
5133 setattr(i, "regular_attr", 102)
5134 assert i.regular_attr == 102
5135 with assertRaises(AttributeError):
5136 setattr(i, "class_var", "z")
5137 with assertRaises(AttributeError):
5138 setattr(i, "const", 44)
5139
5140 i.four = [4,4]
5141 assert i.four == [4,4]
5142 i.regular_attr = 103
5143 assert i.regular_attr == 103
5144 with assertRaises(AttributeError):
5145 i.const = 45
5146
5147 # Doesn't work because there's no __delattr__.
5148 with assertRaises(AttributeError):
5149 del i.four
5150
5151 def test_setattr_inherited() -> None:
5152 i = SetAttrInherited(99, {"one": 1})
5153 assert i.class_var == "x"
5154 assert i.regular_attr == 99
5155 assert i.one == 1
5156 assert i.two == None
5157 assert i.const == 42
5158 i = i
5159
5160 i.__setattr__("two", "2")
5161 assert i.two == "2"
5162 i.__setattr__("regular_attr", 101)
5163 assert i.regular_attr == 101
5164 with assertRaises(AttributeError):
5165 i.__setattr__("class_var", "y")
5166 with assertRaises(AttributeError):
5167 i.__setattr__("const", 43)
5168
5169 setattr(i, "three", (3,3,3))
5170 assert i.three == (3,3,3)
5171 setattr(i, "regular_attr", 102)
5172 assert i.regular_attr == 102
5173 with assertRaises(AttributeError):
5174 setattr(i, "class_var", "z")
5175 with assertRaises(AttributeError):
5176 setattr(i, "const", 44)
5177
5178 i.four = [4,4]
5179 assert i.four == [4,4]
5180 i.regular_attr = 103
5181 assert i.regular_attr == 103
5182 with assertRaises(AttributeError):
5183 i.const = 45
5184
5185 # Doesn't work because there's no __delattr__.
5186 with assertRaises(AttributeError):
5187 del i.four
5188
5189 def test_setattr_overridden() -> None:
5190 i = SetAttrOverridden(99, 1, {"one": 1})
5191 assert i.class_var == "x"
5192 assert i.subclass_var == "y"
5193 assert i.regular_attr == 99
5194 assert i.sub_attr == 1
5195 assert i.one == 1
5196 assert i.two == None
5197 assert i.const == 42
5198 i = i
5199
5200 i.__setattr__("two", "2")
5201 assert i.two == "2"
5202 i.__setattr__("regular_attr", 101)
5203 assert i.regular_attr == 101
5204 i.__setattr__("sub_attr", 2)
5205 assert i.sub_attr == 2
5206 with assertRaises(AttributeError):
5207 i.__setattr__("class_var", "y")
5208 with assertRaises(AttributeError):
5209 i.__setattr__("subclass_var", "a")
5210 with assertRaises(AttributeError):
5211 i.__setattr__("const", 43)
5212
5213 setattr(i, "three", (3,3,3))
5214 assert i.three == (3,3,3)
5215 setattr(i, "regular_attr", 102)
5216 assert i.regular_attr == 102
5217 setattr(i, "sub_attr", 3)
5218 assert i.sub_attr == 3
5219 with assertRaises(AttributeError):
5220 setattr(i, "class_var", "z")
5221 with assertRaises(AttributeError):
5222 setattr(i, "subclass_var", "b")
5223 with assertRaises(AttributeError):
5224 setattr(i, "const", 44)
5225
5226 i.four = [4,4]
5227 assert i.four == [4,4]
5228 i.regular_attr = 103
5229 assert i.regular_attr == 103
5230 i.sub_attr = 4
5231 assert i.sub_attr == 4
5232 with assertRaises(AttributeError):
5233 i.const = 45
5234
5235 del i.four
5236 assert "four" not in i._attributes
5237
5238 delattr(i, "three")
5239 assert "three" not in i._attributes
5240
5241 i.__delattr__("two")
5242 assert "two" not in i._attributes
5243
5244 base_ref: SetAttr = i
5245 setattr(base_ref, "sub_attr", 5)
5246 assert base_ref.sub_attr == 5
5247
5248 base_ref.sub_attr = 6
5249 assert base_ref.sub_attr == 6
5250
5251 with assertRaises(AttributeError):
5252 setattr(base_ref, "subclass_var", "c")
5253
5254 base_ref.new_attr = "new_attr"
5255 assert base_ref.new_attr == "new_attr"
5256
5257 del base_ref.new_attr
5258 assert "new_attr" not in base_ref._attributes
5259
5260 def test_setattr_nonnative() -> None:
5261 i = SetAttrNonNative(99, {"one": 1})
5262 assert i.class_var == "x"
5263 assert i.regular_attr == 99
5264 assert i.one == 1
5265 assert i.two == None
5266 assert i.const == 42
5267 i = i
5268
5269 i.__setattr__("two", "2")
5270 assert i.two == "2"
5271 i.__setattr__("regular_attr", 101)
5272 assert i.regular_attr == 101
5273 with assertRaises(AttributeError):
5274 i.__setattr__("class_var", "y")
5275 with assertRaises(AttributeError):
5276 i.__setattr__("const", 43)
5277
5278 setattr(i, "three", (3,3,3))
5279 assert i.three == (3,3,3)
5280 setattr(i, "regular_attr", 102)
5281 assert i.regular_attr == 102
5282 with assertRaises(AttributeError):
5283 setattr(i, "class_var", "z")
5284 with assertRaises(AttributeError):
5285 setattr(i, "const", 44)
5286
5287 i.four = [4,4]
5288 assert i.four == [4,4]
5289 i.regular_attr = 103
5290 assert i.regular_attr == 103
5291 with assertRaises(AttributeError):
5292 i.const = 45
5293
5294 # Doesn't work because there's no __delattr__.
5295 with assertRaises(AttributeError):
5296 del i.four
5297
5298 def test_no_setattr() -> None:
5299 i = NoSetAttr(99)
5300 i.super_setattr("attr", 100)
5301 assert i.attr == 100
5302
5303 i.object_setattr("attr", 101)
5304 assert i.attr == 101
5305
5306 object.__setattr__(i, "attr", 102)
5307 assert i.attr == 102
5308
5309 with assertRaises(AttributeError):
5310 i.super_setattr("not_attr", 100)
5311
5312 with assertRaises(AttributeError):
5313 i.object_setattr("not_attr", 101)
5314
5315 with assertRaises(AttributeError):
5316 object.__setattr__(i, "not_attr", 102)
5317
5318 def test_no_setattr_nonnative() -> None:
5319 i = NoSetAttrNonNative(99)
5320 i.super_setattr("attr", 100)
5321 assert i.attr == 100
5322
5323 i.object_setattr("attr", 101)
5324 assert i.attr == 101
5325
5326 object.__setattr__(i, "attr", 102)
5327 assert i.attr == 102
5328
5329 i.super_setattr("one", 100)
5330 assert i.one == 100
5331
5332 i.object_setattr("two", 101)
5333 assert i.two == 101
5334
5335 object.__setattr__(i, "three", 102)
5336 assert i.three == 102
5337
5338 i = i
5339
5340 del i.three
5341 assert i.three == None
5342
5343 delattr(i, "two")
5344 assert i.two == None
5345
5346 object.__delattr__(i, "one")
5347 assert i.one == None
5348
5349 [typing fixtures/typing-full.pyi]
5350
5351 [case testDunderSetAttrInterpreted]
5352 from mypy_extensions import mypyc_attr
5353 from typing import ClassVar
5354
5355 class SetAttr:
5356 _attributes: dict[str, object]
5357 regular_attr: int
5358 class_var: ClassVar[str] = "x"
5359 const: int = 42
5360
5361 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
5362 super().__setattr__("_attributes", extra_attrs)
5363 super().__setattr__("regular_attr", regular_attr)
5364
5365 def __setattr__(self, key: str, val: object) -> None:
5366 if key == "regular_attr":
5367 super().__setattr__("regular_attr", val)
5368 elif key == "class_var" or key == "const":
5369 raise AttributeError()
5370 else:
5371 self._attributes[key] = val
5372
5373 def __getattr__(self, key: str) -> object:
5374 return self._attributes.get(key)
5375
5376 class SetAttrInherited(SetAttr):
5377 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
5378 super().__init__(regular_attr, extra_attrs)
5379
5380 class SetAttrOverridden(SetAttr):
5381 sub_attr: int
5382 subclass_var: ClassVar[str] = "y"
5383
5384 def __init__(self, regular_attr: int, sub_attr: int, extra_attrs: dict[str, object]) -> None:
5385 super().__init__(regular_attr, extra_attrs)
5386 object.__setattr__(self, "sub_attr", sub_attr)
5387
5388 def __setattr__(self, key: str, val: object) -> None:
5389 if key == "sub_attr":
5390 object.__setattr__(self, "sub_attr", val)
5391 elif key == "subclass_var":
5392 raise AttributeError()
5393 else:
5394 super().__setattr__(key, val)
5395
5396 def __delattr__(self, key: str) -> None:
5397 del self._attributes[key]
5398
5399 @mypyc_attr(native_class=False)
5400 class SetAttrNonNative:
5401 _attributes: dict[str, object]
5402 regular_attr: int
5403 class_var: ClassVar[str] = "x"
5404 const: int = 42
5405
5406 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
5407 super().__setattr__("_attributes", extra_attrs)
5408 super().__setattr__("regular_attr", regular_attr)
5409
5410 def __setattr__(self, key: str, val: object) -> None:
5411 if key == "regular_attr":
5412 super().__setattr__("regular_attr", val)
5413 elif key == "class_var" or key == "const":
5414 raise AttributeError()
5415 else:
5416 self._attributes[key] = val
5417
5418 def __getattr__(self, key: str) -> object:
5419 return self._attributes.get(key)
5420
5421 class NoSetAttr:
5422 def __init__(self, attr: int) -> None:
5423 self.attr = attr
5424
5425 def object_setattr(self, attr: str, val: object) -> None:
5426 object.__setattr__(self, attr, val)
5427
5428 def super_setattr(self, attr: str, val: object) -> None:
5429 super().__setattr__(attr, val)
5430
5431 @mypyc_attr(native_class=False)
5432 class NoSetAttrNonNative:
5433 def __init__(self, attr: int) -> None:
5434 self.attr = attr
5435
5436 def object_setattr(self, attr: str, val: object) -> None:
5437 object.__setattr__(self, attr, val)
5438
5439 def super_setattr(self, attr: str, val: object) -> None:
5440 super().__setattr__(attr, val)
5441
5442 def __getattr__(self, attr: str) -> object:
5443 pass
5444
5445 [file driver.py]
5446 from native import SetAttr, SetAttrInherited, SetAttrOverridden, SetAttrNonNative, NoSetAttr, NoSetAttrNonNative
5447 from testutil import assertRaises
5448
5449 def test_setattr() -> None:
5450 i = SetAttr(99, {"one": 1})
5451 assert i.class_var == "x"
5452 assert i.regular_attr == 99
5453 assert i.one == 1
5454 assert i.two == None
5455 assert i.const == 42
5456
5457 i.__setattr__("two", "2")
5458 assert i.two == "2"
5459 i.__setattr__("regular_attr", 101)
5460 assert i.regular_attr == 101
5461 with assertRaises(AttributeError):
5462 i.__setattr__("class_var", "y")
5463 with assertRaises(AttributeError):
5464 i.__setattr__("const", 43)
5465
5466 setattr(i, "three", (3,3,3))
5467 assert i.three == (3,3,3)
5468 setattr(i, "regular_attr", 102)
5469 assert i.regular_attr == 102
5470 with assertRaises(AttributeError):
5471 setattr(i, "class_var", "z")
5472 with assertRaises(AttributeError):
5473 setattr(i, "const", 44)
5474
5475 i.four = [4,4]
5476 assert i.four == [4,4]
5477 i.regular_attr = 103
5478 assert i.regular_attr == 103
5479 with assertRaises(AttributeError):
5480 i.const = 45
5481
5482 # Doesn't work because there's no __delattr__.
5483 with assertRaises(AttributeError):
5484 del i.four
5485
5486 def test_setattr_inherited() -> None:
5487 i = SetAttrInherited(99, {"one": 1})
5488 assert i.class_var == "x"
5489 assert i.regular_attr == 99
5490 assert i.one == 1
5491 assert i.two == None
5492 assert i.const == 42
5493
5494 i.__setattr__("two", "2")
5495 assert i.two == "2"
5496 i.__setattr__("regular_attr", 101)
5497 assert i.regular_attr == 101
5498 with assertRaises(AttributeError):
5499 i.__setattr__("class_var", "y")
5500 with assertRaises(AttributeError):
5501 i.__setattr__("const", 43)
5502
5503 setattr(i, "three", (3,3,3))
5504 assert i.three == (3,3,3)
5505 setattr(i, "regular_attr", 102)
5506 assert i.regular_attr == 102
5507 with assertRaises(AttributeError):
5508 setattr(i, "class_var", "z")
5509 with assertRaises(AttributeError):
5510 setattr(i, "const", 44)
5511
5512 i.four = [4,4]
5513 assert i.four == [4,4]
5514 i.regular_attr = 103
5515 assert i.regular_attr == 103
5516 with assertRaises(AttributeError):
5517 i.const = 45
5518
5519 # Doesn't work because there's no __delattr__.
5520 with assertRaises(AttributeError):
5521 del i.four
5522
5523 def test_setattr_overridden() -> None:
5524 i = SetAttrOverridden(99, 1, {"one": 1})
5525 assert i.class_var == "x"
5526 assert i.subclass_var == "y"
5527 assert i.regular_attr == 99
5528 assert i.sub_attr == 1
5529 assert i.one == 1
5530 assert i.two == None
5531 assert i.const == 42
5532
5533 i.__setattr__("two", "2")
5534 assert i.two == "2"
5535 i.__setattr__("regular_attr", 101)
5536 assert i.regular_attr == 101
5537 i.__setattr__("sub_attr", 2)
5538 assert i.sub_attr == 2
5539 with assertRaises(AttributeError):
5540 i.__setattr__("class_var", "y")
5541 with assertRaises(AttributeError):
5542 i.__setattr__("subclass_var", "a")
5543 with assertRaises(AttributeError):
5544 i.__setattr__("const", 43)
5545
5546 setattr(i, "three", (3,3,3))
5547 assert i.three == (3,3,3)
5548 setattr(i, "regular_attr", 102)
5549 assert i.regular_attr == 102
5550 setattr(i, "sub_attr", 3)
5551 assert i.sub_attr == 3
5552 with assertRaises(AttributeError):
5553 setattr(i, "class_var", "z")
5554 with assertRaises(AttributeError):
5555 setattr(i, "subclass_var", "b")
5556 with assertRaises(AttributeError):
5557 setattr(i, "const", 44)
5558
5559 i.four = [4,4]
5560 assert i.four == [4,4]
5561 i.regular_attr = 103
5562 assert i.regular_attr == 103
5563 i.sub_attr = 4
5564 assert i.sub_attr == 4
5565 with assertRaises(AttributeError):
5566 i.const = 45
5567
5568 del i.four
5569 assert "four" not in i._attributes
5570
5571 delattr(i, "three")
5572 assert "three" not in i._attributes
5573
5574 i.__delattr__("two")
5575 assert "two" not in i._attributes
5576
5577 base_ref: SetAttr = i
5578 setattr(base_ref, "sub_attr", 5)
5579 assert base_ref.sub_attr == 5
5580
5581 base_ref.sub_attr = 6
5582 assert base_ref.sub_attr == 6
5583
5584 with assertRaises(AttributeError):
5585 setattr(base_ref, "subclass_var", "c")
5586
5587 base_ref.new_attr = "new_attr"
5588 assert base_ref.new_attr == "new_attr"
5589
5590 del base_ref.new_attr
5591 assert "new_attr" not in base_ref._attributes
5592
5593 def test_setattr_nonnative() -> None:
5594 i = SetAttrNonNative(99, {"one": 1})
5595 assert i.class_var == "x"
5596 assert i.regular_attr == 99
5597 assert i.one == 1
5598 assert i.two == None
5599 assert i.const == 42
5600
5601 i.__setattr__("two", "2")
5602 assert i.two == "2"
5603 i.__setattr__("regular_attr", 101)
5604 assert i.regular_attr == 101
5605 with assertRaises(AttributeError):
5606 i.__setattr__("class_var", "y")
5607 with assertRaises(AttributeError):
5608 i.__setattr__("const", 43)
5609
5610 setattr(i, "three", (3,3,3))
5611 assert i.three == (3,3,3)
5612 setattr(i, "regular_attr", 102)
5613 assert i.regular_attr == 102
5614 with assertRaises(AttributeError):
5615 setattr(i, "class_var", "z")
5616 with assertRaises(AttributeError):
5617 setattr(i, "const", 44)
5618
5619 i.four = [4,4]
5620 assert i.four == [4,4]
5621 i.regular_attr = 103
5622 assert i.regular_attr == 103
5623 with assertRaises(AttributeError):
5624 i.const = 45
5625
5626 # Doesn't work because there's no __delattr__.
5627 with assertRaises(AttributeError):
5628 del i.four
5629
5630 def test_no_setattr() -> None:
5631 i = NoSetAttr(99)
5632 i.super_setattr("attr", 100)
5633 assert i.attr == 100
5634
5635 i.object_setattr("attr", 101)
5636 assert i.attr == 101
5637
5638 object.__setattr__(i, "attr", 102)
5639 assert i.attr == 102
5640
5641 with assertRaises(AttributeError):
5642 i.super_setattr("not_attr", 100)
5643
5644 with assertRaises(AttributeError):
5645 i.object_setattr("not_attr", 101)
5646
5647 with assertRaises(AttributeError):
5648 object.__setattr__(i, "not_attr", 102)
5649
5650 def test_no_setattr_nonnative() -> None:
5651 i = NoSetAttrNonNative(99)
5652 i.super_setattr("attr", 100)
5653 assert i.attr == 100
5654
5655 i.object_setattr("attr", 101)
5656 assert i.attr == 101
5657
5658 object.__setattr__(i, "attr", 102)
5659 assert i.attr == 102
5660
5661 i.super_setattr("one", 100)
5662 assert i.one == 100
5663
5664 i.object_setattr("two", 101)
5665 assert i.two == 101
5666
5667 object.__setattr__(i, "three", 102)
5668 assert i.three == 102
5669
5670 del i.three
5671 assert i.three == None
5672
5673 delattr(i, "two")
5674 assert i.two == None
5675
5676 object.__delattr__(i, "one")
5677 assert i.one == None
5678
5679 test_setattr()
5680 test_setattr_inherited()
5681 test_setattr_overridden()
5682 test_setattr_nonnative()
5683 test_no_setattr()
5684 test_no_setattr_nonnative()
5685
5686 [typing fixtures/typing-full.pyi]
5687
5688 [case testDelAttrWithDeletableAttr]
5689 from testutil import assertRaises
5690
5691 class DelAttr:
5692 __deletable__ = ["del_counter"]
5693
5694 _attributes: dict[str, object]
5695 del_counter: int = 0
5696
5697 def __init__(self) -> None:
5698 object.__setattr__(self, "_attributes", {})
5699
5700 def __setattr__(self, key: str, val: object) -> None:
5701 if key == "del_counter":
5702 object.__setattr__(self, "del_counter", val)
5703 else:
5704 self._attributes[key] = val
5705
5706 def __delattr__(self, key: str) -> None:
5707 if key == "del_counter":
5708 self.del_counter += 1
5709 else:
5710 del self._attributes[key]
5711
5712 def test_deletable_attr() -> None:
5713 i = DelAttr()
5714 assert i.del_counter == 0
5715 del i.del_counter
5716 assert i.del_counter == 1
5717
5718 [case testDelAttrWithDeletableAttrInterpreted]
5719 class DelAttr:
5720 __deletable__ = ["del_counter"]
5721
5722 _attributes: dict[str, object]
5723 del_counter: int = 0
5724
5725 def __init__(self) -> None:
5726 object.__setattr__(self, "_attributes", {})
5727
5728 def __setattr__(self, key: str, val: object) -> None:
5729 if key == "del_counter":
5730 object.__setattr__(self, "del_counter", val)
5731 else:
5732 self._attributes[key] = val
5733
5734 def __delattr__(self, key: str) -> None:
5735 if key == "del_counter":
5736 self.del_counter += 1
5737 else:
5738 del self._attributes[key]
5739
5740 [file driver.py]
5741 from native import DelAttr
5742 from testutil import assertRaises
5743
5744 def test_deletable_attr() -> None:
5745 i = DelAttr()
5746 assert i.del_counter == 0
5747 del i.del_counter
5748 assert i.del_counter == 1
5749
5750 test_deletable_attr()
5751
5752 [case testBufferCorruptedData_librt_internal]
5753 from librt.internal import (
5754 ReadBuffer, read_bool, read_str, read_float, read_int, read_tag, read_bytes
5755 )
5756 from random import randbytes
5757
5758 def check(data: bytes) -> None:
5759 b = ReadBuffer(data)
5760 try:
5761 while True:
5762 read_bool(b)
5763 except ValueError:
5764 pass
5765 b = ReadBuffer(data)
5766 read_tag(b) # Always succeeds
5767 try:
5768 while True:
5769 read_int(b)
5770 except ValueError:
5771 pass
5772 b = ReadBuffer(data)
5773 try:
5774 while True:
5775 read_str(b)
5776 except ValueError:
5777 pass
5778 b = ReadBuffer(data)
5779 try:
5780 while True:
5781 read_bytes(b)
5782 except ValueError:
5783 pass
5784 b = ReadBuffer(data)
5785 try:
5786 while True:
5787 read_float(b)
5788 except ValueError:
5789 pass
5790
5791 import time
5792
5793 def test_read_corrupted_data() -> None:
5794 # Test various deterministic byte sequences (1 to 4 bytes).
5795 t0 = time.time()
5796 for a in range(256):
5797 check(bytes([a]))
5798 for a in range(256):
5799 for b in range(256):
5800 check(bytes([a, b]))
5801 for a in range(32):
5802 for b in range(48):
5803 for c in range(48):
5804 check(bytes([a, b, c]))
5805 for a in range(32):
5806 for b in (0, 5, 17, 34):
5807 for c in (0, 5, 17, 34):
5808 for d in (0, 5, 17, 34):
5809 check(bytes([a, b, c, d]))
5810 # Also test some random data.
5811 for i in range(20000):
5812 data = randbytes(16)
5813 try:
5814 check(data)
5815 except BaseException as e:
5816 print("RANDOMIZED TEST FAILURE -- please open an issue with the following context:")
5817 print(">>>", e, data)
5818 raise
5819
5820 [case testAcyclicClass]
5821 import gc
5822 from mypy_extensions import mypyc_attr
5823
5824 @mypyc_attr(acyclic=True)
5825 class Leaf:
5826 def __init__(self, x: int, s: str) -> None:
5827 self.x = x
5828 self.s = s
5829
5830 def test_basic() -> None:
5831 o = Leaf(5, "hello")
5832 assert o.x == 5
5833 assert o.s == "hello"
5834 o.x = 10
5835 assert o.x == 10
5836
5837 def test_gc_not_tracked() -> None:
5838 o = Leaf(1, "a")
5839 assert not gc.is_tracked(o)
5840
5841 def test_dealloc() -> None:
5842 for i in range(1000):
5843 o = Leaf(i, str(i))
5844 # Just verify no crash or leak during repeated alloc/dealloc
5845
5846 @mypyc_attr(acyclic=True)
5847 class AcyclicBase:
5848 def __init__(self, x: int) -> None:
5849 self.x = x
5850
5851 class DerivedNotAcyclic(AcyclicBase):
5852 """Derived without acyclic -- still participates in GC."""
5853 def __init__(self, x: int, y: str) -> None:
5854 super().__init__(x)
5855 self.y = y
5856
5857 @mypyc_attr(acyclic=True)
5858 class DerivedAcyclic(AcyclicBase):
5859 """Derived with acyclic -- also opts out of GC."""
5860 def __init__(self, x: int, y: str) -> None:
5861 super().__init__(x)
5862 self.y = y
5863
5864 def test_derived_not_acyclic() -> None:
5865 d = DerivedNotAcyclic(3, "hi")
5866 assert d.x == 3
5867 assert d.y == "hi"
5868 # Subclass without @mypyc_attr(acyclic=True) still participates in GC
5869 assert gc.is_tracked(d)
5870
5871 def test_derived_acyclic() -> None:
5872 d = DerivedAcyclic(3, "hi")
5873 assert d.x == 3
5874 assert d.y == "hi"
5875 assert not gc.is_tracked(d)
5876
5877 [case testTraitVtableGrandparentMethod]
5878 from typing import Any
5879 from mypy_extensions import trait
5880
5881 @trait
5882 class Base:
5883 def value(self) -> Any:
5884 return 42
5885
5886 @trait
5887 class Middle(Base):
5888 pass
5889
5890 @trait
5891 class Child(Middle):
5892 def derived(self) -> Any:
5893 return self.value()
5894
5895 class Concrete(Child):
5896 pass
5897
5898 class Sub(Concrete):
5899 def value(self) -> Any:
5900 return 99
5901
5902 [file driver.py]
5903 from native import Concrete, Sub
5904 c = Concrete()
5905 assert c.value() == 42
5906 assert c.derived() == 42
5907 s = Sub()
5908 assert s.value() == 99
5909 assert s.derived() == 99
5910
5911 [case testTraitVtableGrandparentMethodAllowInterpretedSubclasses]
5912 from typing import Any
5913 from mypy_extensions import trait, mypyc_attr
5914
5915 @mypyc_attr(allow_interpreted_subclasses=True)
5916 @trait
5917 class Base:
5918 def value(self) -> Any:
5919 return 42
5920
5921 @mypyc_attr(allow_interpreted_subclasses=True)
5922 @trait
5923 class Middle(Base):
5924 pass
5925
5926 @mypyc_attr(allow_interpreted_subclasses=True)
5927 @trait
5928 class Child(Middle):
5929 def derived(self) -> Any:
5930 return self.value()
5931
5932 @mypyc_attr(allow_interpreted_subclasses=True)
5933 class Concrete(Child):
5934 pass
5935
5936 [file driver.py]
5937 from native import Concrete
5938 c = Concrete()
5939 assert c.value() == 42
5940 assert c.derived() == 42
5941
5942 [case testPropertyShadowVtableGlue]
5943 from typing import List
5944 import mypy_extensions
5945
5946 @mypy_extensions.mypyc_attr(allow_interpreted_subclasses=True)
5947 class Base:
5948 _x: str
5949 _y: List[int]
5950 def __init__(self) -> None:
5951 self._x = ""
5952 self._y = []
5953
5954 @property
5955 def x(self) -> str:
5956 return self._x
5957
5958 @x.setter
5959 def x(self, v: str) -> None:
5960 self._x = v
5961
5962 @property
5963 def y(self) -> List[int]:
5964 return self._y
5965
5966 @y.setter
5967 def y(self, v: List[int]) -> None:
5968 self._y = v
5969
5970 def method(self) -> str:
5971 self.x = "a"
5972 self.y = [1]
5973 return self.x + str(len(self.y))
5974
5975 [file driver.py]
5976 from native import Base
5977
5978 Sub = type("Sub", (Base,), {})
5979 s = Sub()
5980 assert s.method() == "a1"
5981
5982 [case testClassVarSelfReference]
5983 # ClassVar initializers that reference other ClassVars from the same class.
5984 # In CPython, the class body executes as a function where earlier assignments
5985 # are available to later ones. mypyc must replicate this by loading from the
5986 # class being built (type object for ext classes, class dict for non-ext)
5987 # instead of module globals.
5988 from typing import ClassVar, Dict, Set
5989
5990 class Ext:
5991 A: ClassVar[Set[int]] = {1, 2, 3}
5992 B: ClassVar[Set[int]] = {4, 5, 6}
5993 C: ClassVar[Set[int]] = A | B
5994
5995 class ExtChained:
5996 X: ClassVar[Set[int]] = {1, 2}
5997 Y: ClassVar[Set[int]] = X | {3}
5998 Z: ClassVar[Set[int]] = Y | {4}
5999
6000 class ExtDict:
6001 BASE: ClassVar[Dict[str, int]] = {"a": 1, "b": 2}
6002 EXTENDED: ClassVar[Dict[str, int]] = {**BASE, "c": 3}
6003
6004 class ExtSub(Ext):
6005 E: ClassVar[Set[int]] = {7, 8}
6006
6007 [file driver.py]
6008 from native import Ext, ExtChained, ExtDict, ExtSub
6009
6010 assert Ext.A == {1, 2, 3}
6011 assert Ext.B == {4, 5, 6}
6012 assert Ext.C == {1, 2, 3, 4, 5, 6}
6013
6014 assert ExtChained.X == {1, 2}
6015 assert ExtChained.Y == {1, 2, 3}
6016 assert ExtChained.Z == {1, 2, 3, 4}
6017
6018 assert ExtDict.BASE == {"a": 1, "b": 2}
6019 assert ExtDict.EXTENDED == {"a": 1, "b": 2, "c": 3}
6020
6021 assert ExtSub.C == {1, 2, 3, 4, 5, 6}
6022 assert ExtSub.E == {7, 8}
6023
6024 [case testClassVarSelfReferenceNonExt]
6025 # Same as testClassVarSelfReference but for non-extension classes.
6026 from typing import ClassVar, Dict, Set
6027 from mypy_extensions import mypyc_attr
6028
6029 @mypyc_attr(native_class=False)
6030 class NonExt:
6031 A: ClassVar[Set[str]] = {"a", "b"}
6032 B: ClassVar[Set[str]] = {"c"}
6033 C: ClassVar[Set[str]] = A | B
6034
6035 @mypyc_attr(native_class=False)
6036 class NonExtDict:
6037 BASE: ClassVar[Dict[str, int]] = {"x": 1}
6038 EXTENDED: ClassVar[Dict[str, int]] = {**BASE, "y": 2}
6039
6040 @mypyc_attr(native_class=False)
6041 class NonExtChained:
6042 X: ClassVar[Set[int]] = {10}
6043 Y: ClassVar[Set[int]] = X | {20}
6044 Z: ClassVar[Set[int]] = Y | {30}
6045
6046 [file driver.py]
6047 from native import NonExt, NonExtDict, NonExtChained
6048
6049 assert NonExt.A == {"a", "b"}
6050 assert NonExt.B == {"c"}
6051 assert NonExt.C == {"a", "b", "c"}
6052
6053 assert NonExtDict.BASE == {"x": 1}
6054 assert NonExtDict.EXTENDED == {"x": 1, "y": 2}
6055
6056 assert NonExtChained.Z == {10, 20, 30}
6057
6058 [case testPropertyGetterLeak]
6059 class Bar:
6060 pass
6061
6062 class Foo:
6063 def __init__(self) -> None:
6064 self.obj: object = Bar()
6065
6066 @property
6067 def val(self) -> object:
6068 return self.obj
6069
6070 [file other.py]
6071 import gc
6072 from native import Foo, Bar
6073
6074 def check(foo: Foo) -> bool:
6075 return isinstance(foo.val, Bar)
6076
6077 def test_property_getter_no_leak() -> None:
6078 gc.collect()
6079 before = gc.get_objects()
6080 for _ in range(100):
6081 foo = Foo()
6082 check(foo)
6083 gc.collect()
6084 after = gc.get_objects()
6085 diff = len(after) - len(before)
6086 assert diff <= 2, diff
6087
6088 test_property_getter_no_leak()
6089
6090 [file driver.py]
6091 import sys
6092 from other import check
6093 from native import Foo
6094
6095 foo = Foo()
6096 init = sys.getrefcount(foo.obj)
6097 for _ in range(100):
6098 check(foo)
6099 after = sys.getrefcount(foo.obj)
6100 assert after - init == 0, f"Leaked {after - init} refs"
6101
6102 [case testNativeAttrSetterRefcountLeak]
6103 # Setting a native attribute from interpreted code goes through the generated
6104 # getset descriptor setter. For refcounted unboxed types (heap-boxed ints,
6105 # tuples with refcounted items) the setter must take exactly one reference to
6106 # the stored value, not two.
6107 from dataclasses import dataclass
6108 from typing import Tuple
6109
6110 @dataclass
6111 class IntField:
6112 v: int
6113
6114 @dataclass
6115 class TupleField:
6116 v: Tuple[int, int]
6117
6118 [file driver.py]
6119 import sys
6120 from native import IntField, TupleField
6121
6122 # A heap-boxed int (>= 2**62) is stored as a refcounted PyObject*, unlike small
6123 # inline-tagged ints, so an over-incref strands a real reference. Compute the
6124 # values at runtime (not as folded literals): on free-threaded builds code
6125 # constants are immortal, and getrefcount could not observe a leak on them.
6126 shift = 70
6127 BIG = 1 << shift
6128
6129 def check_no_leak(make, value) -> None:
6130 base = sys.getrefcount(value)
6131 objs = [make(value) for _ in range(100)]
6132 alive = sys.getrefcount(value)
6133 # Each live instance must hold exactly one reference to the field value.
6134 assert alive - base == 100, f"expected 100 live refs, got {alive - base}"
6135 del objs
6136 after = sys.getrefcount(value)
6137 assert after == base, f"leaked {after - base} refs"
6138
6139 # The dataclass-generated __init__ stores self.v = v via the descriptor setter.
6140 check_no_leak(IntField, BIG)
6141
6142 # Tuple[int, int] is stored as an unboxed RTuple; its boxed-int elements are
6143 # refcounted, so the setter must not over-incref them either. Use the same int
6144 # in both slots so each instance holds exactly two references to it.
6145 ELEM = 1 << (shift + 1)
6146 base = sys.getrefcount(ELEM)
6147 objs = [TupleField((ELEM, ELEM)) for _ in range(100)]
6148 alive = sys.getrefcount(ELEM)
6149 assert alive - base == 200, f"expected 200 live refs, got {alive - base}"
6150 del objs
6151 assert sys.getrefcount(ELEM) == base, f"tuple field leaked {sys.getrefcount(ELEM) - base} refs"
6152
6153 # Re-assigning through the setter must release the previous value too.
6154 o = IntField(BIG)
6155 base = sys.getrefcount(BIG)
6156 o.v = BIG
6157 o.v = BIG
6158 assert sys.getrefcount(BIG) == base, "reassignment leaked refs"
6159
6160 [case testBorrowedFinalAttributeInLambdaAndNestedFunction]
6161 from typing import Final, Callable
6162
6163 class Box:
6164 def __init__(self, n: int) -> None:
6165 self.n = n
6166
6167 class C:
6168 def __init__(self, b: Box) -> None:
6169 self.b: Final = b
6170
6171 def use(x: Box, y: Box) -> int:
6172 return x.n + y.n
6173
6174 def spend(x: Box) -> Box:
6175 # Allocate a lot so a freed Box slot is likely to be reused, turning any
6176 # use-after-free of a borrowed attribute into an observable wrong result.
6177 junk = [Box(i) for i in range(100)]
6178 return Box(x.n + junk[50].n - 50)
6179
6180 def make_lambda() -> Callable[[], int]:
6181 # The lambda body creates a C, borrows its final attribute, then calls
6182 # spend() (which allocates heavily) before reading the borrow.
6183 return lambda: use(C(Box(111)).b, spend(Box(0)))
6184
6185 def make_nested() -> Callable[[], int]:
6186 def inner() -> int:
6187 return use(C(Box(111)).b, spend(Box(0)))
6188 return inner
6189
6190 def test_borrowed_final_attribute_in_lambda() -> None:
6191 f = make_lambda()
6192 for _ in range(1000):
6193 assert f() == 111
6194
6195 def test_borrowed_final_attribute_in_nested_function() -> None:
6196 g = make_nested()
6197 for _ in range(1000):
6198 assert g() == 111
6199
6200 [case testBorrowedFinalAttributeInComprehension]
6201 from typing import Final
6202
6203 class Box:
6204 def __init__(self, n: int) -> None:
6205 self.n = n
6206
6207 class C:
6208 def __init__(self, b: Box) -> None:
6209 self.b: Final = b
6210
6211 def use(x: Box, y: Box) -> int:
6212 return x.n + y.n
6213
6214 def spend(x: Box) -> Box:
6215 # Allocate a lot so a freed Box slot is likely to be reused, turning any
6216 # use-after-free of a borrowed attribute into an observable wrong result.
6217 junk = [Box(i) for i in range(100)]
6218 return Box(x.n + junk[50].n - 50)
6219
6220 def comp(ns: list[int]) -> list[int]:
6221 # Each iteration allocates a fresh C, borrows its final attribute .b, then
6222 # calls spend() (which allocates heavily) before reading the borrow. The
6223 # borrow container must be kept alive for the current iteration only; if it
6224 # is scoped to the whole (comprehension) expression, the refcount pass
6225 # dec_refs an uninitialized temporary on the loop back-edge and leaks/uses
6226 # freed memory.
6227 return [use(C(Box(111)).b, spend(Box(i))) for i in ns]
6228
6229 def test_borrowed_final_attribute_in_comprehension() -> None:
6230 for _ in range(1000):
6231 assert comp([1, 2, 3, 4, 5]) == [112, 113, 114, 115, 116]