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 testClassDerivedFromIntEnum]
2829 from enum import IntEnum, auto
2830
2831 class Player(IntEnum):
2832 MIN = auto()
2833
2834 print(f'{Player.MIN = }')
2835 [file driver.py]
2836 from native import Player
2837 [out]
2838 Player.MIN = <Player.MIN: 1>
2839
2840 [case testBufferRoundTrip_librt_internal]
2841 from __future__ import annotations
2842
2843 from typing import Final, Any
2844 from mypy_extensions import u8
2845 from librt.internal import (
2846 ReadBuffer, WriteBuffer, write_bool, read_bool, write_str, read_str, write_float, read_float,
2847 write_int, read_int, write_tag, read_tag, write_bytes, read_bytes,
2848 cache_version,
2849 )
2850
2851 from testutil import assertRaises
2852
2853 Tag = u8
2854 TAG_A: Final[Tag] = 33
2855 TAG_B: Final[Tag] = 255
2856 TAG_SPECIAL: Final[Tag] = 239
2857
2858 def test_buffer_basic() -> None:
2859 assert cache_version() == 0
2860 w = WriteBuffer()
2861 write_str(w, "foo")
2862 r = ReadBuffer(w.getvalue())
2863 assert read_str(r) == "foo"
2864
2865 def test_buffer_grow() -> None:
2866 w = WriteBuffer()
2867 n = 100 * 1000
2868 for i in range(n):
2869 write_int(w, i & 63)
2870 r = ReadBuffer(w.getvalue())
2871 for i in range(n):
2872 assert read_int(r) == (i & 63)
2873 with assertRaises(ValueError):
2874 read_int(r)
2875
2876 def test_buffer_primitive_types() -> None:
2877 a1: Any = WriteBuffer()
2878 w: WriteBuffer = a1
2879 write_str(w, "foo")
2880 data = w.getvalue()
2881 assert read_str(ReadBuffer(data)) == "foo"
2882 a2: Any = ReadBuffer(b"foo")
2883 with assertRaises(TypeError):
2884 w2: WriteBuffer = a2
2885
2886 a3: Any = ReadBuffer(data)
2887 r: ReadBuffer = a3
2888 assert read_str(r) == "foo"
2889 a4: Any = WriteBuffer()
2890 with assertRaises(TypeError):
2891 r2: ReadBuffer = a4
2892
2893 def test_type_check_args_in_write_functions() -> None:
2894 # Test calling wrapper functions with invalid arg types
2895 from librt import internal
2896 alias: Any = internal
2897 w = WriteBuffer()
2898 with assertRaises(TypeError):
2899 alias.write_str(None, "foo")
2900 with assertRaises(TypeError):
2901 alias.write_str(w, None)
2902 with assertRaises(TypeError):
2903 alias.write_bool(None, True)
2904 with assertRaises(TypeError):
2905 alias.write_bool(w, None)
2906 with assertRaises(TypeError):
2907 alias.write_bytes(None, b"foo")
2908 with assertRaises(TypeError):
2909 alias.write_bytes(w, None)
2910 with assertRaises(TypeError):
2911 alias.write_float(None, 1.5)
2912 with assertRaises(TypeError):
2913 alias.write_float(w, None)
2914 with assertRaises(TypeError):
2915 alias.write_int(None, 15)
2916 with assertRaises(TypeError):
2917 alias.write_int(w, None)
2918 with assertRaises(TypeError):
2919 alias.write_tag(None, 15)
2920 with assertRaises(TypeError):
2921 alias.write_tag(w, None)
2922
2923 def test_type_check_buffer_in_read_functions() -> None:
2924 # Test calling wrapper functions with invalid arg types
2925 from librt import internal
2926 alias: Any = internal
2927 with assertRaises(TypeError):
2928 alias.read_str(None)
2929 with assertRaises(TypeError):
2930 alias.read_bool(None)
2931 with assertRaises(TypeError):
2932 alias.read_bytes(None)
2933 with assertRaises(TypeError):
2934 alias.read_float(None)
2935 with assertRaises(TypeError):
2936 alias.read_int(None)
2937 with assertRaises(TypeError):
2938 alias.read_tag(None)
2939
2940 def test_buffer_roundtrip() -> None:
2941 b: WriteBuffer | ReadBuffer
2942 b = WriteBuffer()
2943 write_str(b, "foo")
2944 write_bool(b, True)
2945 write_str(b, "bar" * 1000)
2946 write_bool(b, False)
2947 write_bytes(b, b"bar")
2948 write_bytes(b, b"bar" * 100)
2949 write_bytes(b, b"")
2950 write_bytes(b, b"a" * 117)
2951 write_bytes(b, b"a" * 118)
2952 write_float(b, 0.1)
2953 write_float(b, -1.0)
2954 write_float(b, -113.0)
2955 write_int(b, 0)
2956 write_int(b, 1)
2957 write_tag(b, TAG_A)
2958 write_tag(b, TAG_SPECIAL)
2959 write_tag(b, TAG_B)
2960 write_int(b, 2)
2961 write_int(b, 2 ** 85)
2962 write_int(b, 255)
2963 write_int(b, -1)
2964 write_int(b, -255)
2965 write_int(b, 536860911)
2966 write_int(b, 536860912)
2967 write_int(b, 1234567891)
2968
2969 b = ReadBuffer(b.getvalue())
2970 assert read_str(b) == "foo"
2971 assert read_bool(b) is True
2972 assert read_str(b) == "bar" * 1000
2973 assert read_bool(b) is False
2974 assert read_bytes(b) == b"bar"
2975 assert read_bytes(b) == b"bar" * 100
2976 assert read_bytes(b) == b""
2977 assert read_bytes(b) == b"a" * 117
2978 assert read_bytes(b) == b"a" * 118
2979 assert read_float(b) == 0.1
2980 assert read_float(b) == -1.0
2981 assert read_float(b) == -113.0
2982 assert read_int(b) == 0
2983 assert read_int(b) == 1
2984 assert read_tag(b) == TAG_A
2985 assert read_tag(b) == TAG_SPECIAL
2986 assert read_tag(b) == TAG_B
2987 assert read_int(b) == 2
2988 assert read_int(b) == 2 ** 85
2989 assert read_int(b) == 255
2990 assert read_int(b) == -1
2991 assert read_int(b) == -255
2992 assert read_int(b) == 536860911
2993 assert read_int(b) == 536860912
2994 assert read_int(b) == 1234567891
2995
2996 def test_buffer_int_size() -> None:
2997 b: WriteBuffer | ReadBuffer
2998 for i in (-10, -9, 0, 116, 117):
2999 b = WriteBuffer()
3000 write_int(b, i)
3001 assert len(b.getvalue()) == 1
3002 b = ReadBuffer(b.getvalue())
3003 assert read_int(b) == i
3004 for i in (-100, -11, 118, 12344, 16283):
3005 b = WriteBuffer()
3006 write_int(b, i)
3007 assert len(b.getvalue()) == 2
3008 b = ReadBuffer(b.getvalue())
3009 assert read_int(b) == i
3010 for i in (-10000, 16284, 123456789):
3011 b = WriteBuffer()
3012 write_int(b, i)
3013 assert len(b.getvalue()) == 4
3014 b = ReadBuffer(b.getvalue())
3015 assert read_int(b) == i
3016
3017 def test_buffer_int_powers() -> None:
3018 # 0, 1, 2 are tested above
3019 for p in range(2, 200):
3020 b = WriteBuffer()
3021 write_int(b, 1 << p)
3022 write_int(b, (1 << p) - 1)
3023 write_int(b, -1 << p)
3024 write_int(b, (-1 << p) + 1)
3025 rb = ReadBuffer(b.getvalue())
3026 assert read_int(rb) == 1 << p
3027 assert read_int(rb) == (1 << p) - 1
3028 assert read_int(rb) == -1 << p
3029 assert read_int(rb) == (-1 << p) + 1
3030
3031 def test_positive_long_int_serialized_bytes() -> None:
3032 b = WriteBuffer()
3033 n = 0x123456789ab
3034 write_int(b, n)
3035 x = b.getvalue()
3036 # Two prefix bytes, followed by little endian encoded integer in variable-length format
3037 assert x == b"\x0f\x2c\xab\x89\x67\x45\x23\x01"
3038 rb = ReadBuffer(x)
3039 assert read_int(rb) == n
3040
3041 def test_negative_long_int_serialized_bytes() -> None:
3042 b = WriteBuffer()
3043 n = -0x123456789abcde
3044 write_int(b, n)
3045 x = b.getvalue()
3046 assert x == b"\x0f\x32\xde\xbc\x9a\x78\x56\x34\x12"
3047 rb = ReadBuffer(x)
3048 assert read_int(rb) == n
3049
3050 def test_buffer_str_size() -> None:
3051 b: WriteBuffer | ReadBuffer
3052 for s in ("", "a", "a" * 117):
3053 b = WriteBuffer()
3054 write_str(b, s)
3055 assert len(b.getvalue()) == len(s) + 1
3056 b = ReadBuffer(b.getvalue())
3057 assert read_str(b) == s
3058
3059 for s in ("a" * 118, "a" * 16283):
3060 b = WriteBuffer()
3061 write_str(b, s)
3062 assert len(b.getvalue()) == len(s) + 2
3063 b = ReadBuffer(b.getvalue())
3064 assert read_str(b) == s
3065
3066 [file driver.py]
3067 from native import *
3068
3069 test_buffer_basic()
3070 test_buffer_grow()
3071 test_buffer_primitive_types()
3072 test_type_check_args_in_write_functions()
3073 test_type_check_buffer_in_read_functions()
3074 test_buffer_roundtrip()
3075 test_buffer_int_size()
3076 test_buffer_str_size()
3077 test_buffer_int_powers()
3078 test_positive_long_int_serialized_bytes()
3079 test_negative_long_int_serialized_bytes()
3080
3081 def test_buffer_basic_interpreted() -> None:
3082 b = WriteBuffer()
3083 write_str(b, "foo")
3084 b = ReadBuffer(b.getvalue())
3085 assert read_str(b) == "foo"
3086
3087 def test_buffer_roundtrip_interpreted() -> None:
3088 b = WriteBuffer()
3089 write_str(b, "foo")
3090 write_bool(b, True)
3091 write_str(b, "bar" * 1000)
3092 write_bool(b, False)
3093 write_bytes(b, b"bar")
3094 write_bytes(b, b"bar" * 100)
3095 write_bytes(b, b"")
3096 write_bytes(b, b"a" * 117)
3097 write_bytes(b, b"a" * 118)
3098 write_float(b, 0.1)
3099 write_int(b, 0)
3100 write_int(b, 1)
3101 write_tag(b, 33)
3102 write_tag(b, 239)
3103 write_tag(b, 255)
3104 write_int(b, 2)
3105 write_int(b, 2 ** 85)
3106 write_int(b, 255)
3107 write_int(b, -1)
3108 write_int(b, -255)
3109 write_int(b, 536860911)
3110 write_int(b, 536860912)
3111 write_int(b, 1234567891)
3112
3113 b = ReadBuffer(b.getvalue())
3114 assert read_str(b) == "foo"
3115 assert read_bool(b) is True
3116 assert read_str(b) == "bar" * 1000
3117 assert read_bool(b) is False
3118 assert read_bytes(b) == b"bar"
3119 assert read_bytes(b) == b"bar" * 100
3120 assert read_bytes(b) == b""
3121 assert read_bytes(b) == b"a" * 117
3122 assert read_bytes(b) == b"a" * 118
3123 assert read_float(b) == 0.1
3124 assert read_int(b) == 0
3125 assert read_int(b) == 1
3126 assert read_tag(b) == 33
3127 assert read_tag(b) == 239
3128 assert read_tag(b) == 255
3129 assert read_int(b) == 2
3130 assert read_int(b) == 2 ** 85
3131 assert read_int(b) == 255
3132 assert read_int(b) == -1
3133 assert read_int(b) == -255
3134 assert read_int(b) == 536860911
3135 assert read_int(b) == 536860912
3136 assert read_int(b) == 1234567891
3137
3138 def test_buffer_int_size_interpreted() -> None:
3139 for i in (-10, -9, 0, 116, 117):
3140 b = WriteBuffer()
3141 write_int(b, i)
3142 assert len(b.getvalue()) == 1
3143 b = ReadBuffer(b.getvalue())
3144 assert read_int(b) == i
3145 for i in (-100, -11, 118, 12344, 16283):
3146 b = WriteBuffer()
3147 write_int(b, i)
3148 assert len(b.getvalue()) == 2
3149 b = ReadBuffer(b.getvalue())
3150 assert read_int(b) == i
3151 for i in (-10000, 16284, 123456789):
3152 b = WriteBuffer()
3153 write_int(b, i)
3154 assert len(b.getvalue()) == 4
3155 b = ReadBuffer(b.getvalue())
3156 assert read_int(b) == i
3157
3158 def test_buffer_int_powers_interpreted() -> None:
3159 # 0, 1, 2 are tested above
3160 for p in range(2, 9):
3161 b = WriteBuffer()
3162 write_int(b, 1 << p)
3163 write_int(b, -1 << p)
3164 b = ReadBuffer(b.getvalue())
3165 assert read_int(b) == 1 << p
3166 assert read_int(b) == -1 << p
3167
3168 def test_buffer_str_size_interpreted() -> None:
3169 for s in ("", "a", "a" * 117):
3170 b = WriteBuffer()
3171 write_str(b, s)
3172 assert len(b.getvalue()) == len(s) + 1
3173 b = ReadBuffer(b.getvalue())
3174 assert read_str(b) == s
3175
3176 for s in ("a" * 118, "a" * 16283):
3177 b = WriteBuffer()
3178 write_str(b, s)
3179 assert len(b.getvalue()) == len(s) + 2
3180 b = ReadBuffer(b.getvalue())
3181 assert read_str(b) == s
3182
3183 test_buffer_basic_interpreted()
3184 test_buffer_roundtrip_interpreted()
3185 test_buffer_int_size_interpreted()
3186 test_buffer_str_size_interpreted()
3187 test_buffer_int_powers_interpreted()
3188
3189 [case testBufferEmpty_librt_internal]
3190 from librt.internal import WriteBuffer, ReadBuffer, write_int, read_int
3191
3192 def test_empty() -> None:
3193 b = WriteBuffer()
3194 write_int(b, 42)
3195 b1 = ReadBuffer(b.getvalue())
3196 assert read_int(b1) == 42
3197
3198 [case testEnumMethodCalls]
3199 from enum import Enum
3200 from typing import overload, Optional, Union
3201
3202 class C:
3203 def foo(self, x: Test) -> bool:
3204 assert Test.ONE.is_one()
3205 assert x.next(2) == Test.THREE
3206 assert x.prev(2) == Test.ONE
3207 assert x.enigma(22)
3208 assert x.enigma("22") == 22
3209 return x.is_one(inverse=True)
3210
3211 class Test(Enum):
3212 ONE = 1
3213 TWO = 2
3214 THREE = 3
3215
3216 def is_one(self, *, inverse: bool = False) -> bool:
3217 if inverse:
3218 return self != Test.ONE
3219 return self == Test.ONE
3220
3221 @classmethod
3222 def next(cls, val: int) -> Test:
3223 return cls(val + 1)
3224
3225 @staticmethod
3226 def prev(val: int) -> Test:
3227 return Test(val - 1)
3228
3229 @overload
3230 def enigma(self, val: int) -> bool: ...
3231 @overload
3232 def enigma(self, val: Optional[str] = None) -> int: ...
3233 def enigma(self, val: Union[int, str, None] = None) -> Union[int, bool]:
3234 if isinstance(val, int):
3235 return self.is_one()
3236 return 22
3237 [file driver.py]
3238 from native import Test, C
3239
3240 assert Test.ONE.is_one()
3241 assert Test.TWO.is_one(inverse=True)
3242 assert not C().foo(Test.ONE)
3243 assert Test.next(2) == Test.THREE
3244 assert Test.prev(2) == Test.ONE
3245 assert Test.ONE.enigma(22)
3246 assert Test.ONE.enigma("22") == 22
3247
3248 [case testStaticCallsWithUnpackingArgs]
3249 from typing import Tuple
3250
3251 class Foo:
3252 @staticmethod
3253 def static(a: int, b: int, c: int) -> Tuple[int, int, int]:
3254 return (c+1, a+2, b+3)
3255
3256 @classmethod
3257 def clsmethod(cls, a: int, b: int, c: int) -> Tuple[int, int, int]:
3258 return (c+1, a+2, b+3)
3259
3260
3261 print(Foo.static(*[10, 20, 30]))
3262 print(Foo.static(*(40, 50), *[60]))
3263 assert Foo.static(70, 80, *[90]) == Foo.clsmethod(70, *(80, 90))
3264
3265 [file driver.py]
3266 import native
3267
3268 [out]
3269 (31, 12, 23)
3270 (61, 42, 53)
3271
3272 [case testDataclassInitVar]
3273 import dataclasses
3274
3275 @dataclasses.dataclass
3276 class C:
3277 init_v: dataclasses.InitVar[int]
3278 v: float = dataclasses.field(init=False)
3279
3280 def __post_init__(self, init_v):
3281 self.v = init_v + 0.1
3282
3283 [file driver.py]
3284 import native
3285 print(native.C(22).v)
3286
3287 [out]
3288 22.1
3289
3290 [case testLastParentEnum]
3291 from enum import Enum
3292
3293 class ColorCode(str, Enum):
3294 OKGREEN = "okgreen"
3295
3296 [file driver.py]
3297 import native
3298 print(native.ColorCode.OKGREEN.value)
3299
3300 [out]
3301 okgreen
3302
3303 [case testAttrWithSlots]
3304 import attr
3305
3306 @attr.s(slots=True)
3307 class A:
3308 ints: list[int] = attr.ib()
3309
3310 [file driver.py]
3311 import native
3312 print(native.A(ints=[1, -17]).ints)
3313
3314 [out]
3315 \[1, -17]
3316
3317 [case testDataclassClassReference]
3318 from __future__ import annotations
3319 from dataclasses import dataclass
3320
3321 class BackwardDefinedClass:
3322 pass
3323
3324 @dataclass
3325 class Data:
3326 bitem: BackwardDefinedClass
3327 bitems: 'BackwardDefinedClass'
3328 fitem: ForwardDefinedClass
3329 fitems: 'ForwardDefinedClass'
3330
3331 class ForwardDefinedClass:
3332 pass
3333
3334 def test_function():
3335 d = Data(
3336 bitem=BackwardDefinedClass(),
3337 bitems=BackwardDefinedClass(),
3338 fitem=ForwardDefinedClass(),
3339 fitems=ForwardDefinedClass(),
3340 )
3341 assert(isinstance(d.bitem, BackwardDefinedClass))
3342 assert(isinstance(d.bitems, BackwardDefinedClass))
3343 assert(isinstance(d.fitem, ForwardDefinedClass))
3344 assert(isinstance(d.fitems, ForwardDefinedClass))
3345
3346 [case testDelForDictSubclass]
3347 events: list[str] = []
3348
3349 class Item:
3350 def __del__(self) -> None:
3351 events.append("deleting Item")
3352
3353 class DictSubclass(dict):
3354 def __del__(self) -> None:
3355 events.append("deleting DictSubclass")
3356
3357 def test_dict_subclass_dealloc() -> None:
3358 d = DictSubclass()
3359 d["item"] = Item()
3360 del d
3361
3362 [file driver.py]
3363 import sys
3364
3365 from native import events, test_dict_subclass_dealloc
3366
3367 test_dict_subclass_dealloc()
3368
3369 expected_events: list[str] = []
3370
3371 # TODO: Fix when compiling for older python.
3372 # The user-defined __del__ method is currently only invoked when __dict__ is a managed dict
3373 # because calling __del__ in tp_clear on older python crashes.
3374 if sys.version_info >= (3, 12):
3375 expected_events.append("deleting DictSubclass")
3376 expected_events.append("deleting Item")
3377
3378 assert events == expected_events, events
3379
3380 [case testDel]
3381 class A:
3382 def __del__(self):
3383 print("deleting A...")
3384
3385 class B:
3386 def __del__(self):
3387 print("deleting B...")
3388
3389 class C(B):
3390 def __init__(self):
3391 self.a = A()
3392
3393 def __del__(self):
3394 print("deleting C...")
3395 super().__del__()
3396
3397 class D(A):
3398 pass
3399
3400 # Just make sure that this class compiles (see issue mypy#19175). testDelForDictSubclass tests for
3401 # correct output.
3402 class NormDict(dict):
3403 def __del__(self) -> None:
3404 pass
3405
3406 [file driver.py]
3407 import native
3408 native.C()
3409 native.D()
3410
3411 [out]
3412 deleting C...
3413 deleting B...
3414 deleting A...
3415 deleting A...
3416
3417 [case testDelCircular]
3418 import dataclasses
3419 import typing
3420
3421 i: int = 1
3422
3423 @dataclasses.dataclass
3424 class C:
3425 var: typing.Optional["C"] = dataclasses.field(default=None)
3426
3427 def __del__(self):
3428 global i
3429 print(f"deleting C{i}...")
3430 i = i + 1
3431
3432 [file driver.py]
3433 import native
3434 import gc
3435
3436 c1 = native.C()
3437 c2 = native.C()
3438 c1.var = c2
3439 c2.var = c1
3440 del c1
3441 del c2
3442 gc.collect()
3443
3444 [out]
3445 deleting C1...
3446 deleting C2...
3447
3448 [case testDelException]
3449 # 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.
3450 class F:
3451 def __del__(self):
3452 if True:
3453 raise Exception("e2")
3454
3455 [file driver.py]
3456 import native
3457 f = native.F()
3458 del f
3459
3460 [out]
3461 Exception ignored in: <native.F object at 0x000000000000>
3462 Traceback (most recent call last):
3463 File "native.py", line 5, in __del__
3464 raise Exception("e2")
3465 Exception: e2
3466
3467 [case testMypycAttrNativeClass]
3468 from mypy_extensions import mypyc_attr
3469 from testutil import assertRaises
3470
3471 @mypyc_attr(native_class=False)
3472 class AnnontatedNonExtensionClass:
3473 pass
3474
3475 class DerivedClass(AnnontatedNonExtensionClass):
3476 pass
3477
3478 class ImplicitExtensionClass():
3479 pass
3480
3481 @mypyc_attr(native_class=True)
3482 class AnnotatedExtensionClass():
3483 pass
3484
3485 def test_function():
3486 setattr(AnnontatedNonExtensionClass, 'attr_class', 5)
3487 assert(hasattr(AnnontatedNonExtensionClass, 'attr_class') == True)
3488 assert(getattr(AnnontatedNonExtensionClass, 'attr_class') == 5)
3489 delattr(AnnontatedNonExtensionClass, 'attr_class')
3490 assert(hasattr(AnnontatedNonExtensionClass, 'attr_class') == False)
3491
3492 inst = AnnontatedNonExtensionClass()
3493 setattr(inst, 'attr_instance', 6)
3494 assert(hasattr(inst, 'attr_instance') == True)
3495 assert(getattr(inst, 'attr_instance') == 6)
3496 delattr(inst, 'attr_instance')
3497 assert(hasattr(inst, 'attr_instance') == False)
3498
3499 setattr(DerivedClass, 'attr_class', 5)
3500 assert(hasattr(DerivedClass, 'attr_class') == True)
3501 assert(getattr(DerivedClass, 'attr_class') == 5)
3502 delattr(DerivedClass, 'attr_class')
3503 assert(hasattr(DerivedClass, 'attr_class') == False)
3504
3505 derived_inst = DerivedClass()
3506 setattr(derived_inst, 'attr_instance', 6)
3507 assert(hasattr(derived_inst, 'attr_instance') == True)
3508 assert(getattr(derived_inst, 'attr_instance') == 6)
3509 delattr(derived_inst, 'attr_instance')
3510 assert(hasattr(derived_inst, 'attr_instance') == False)
3511
3512 ext_inst = ImplicitExtensionClass()
3513 with assertRaises(AttributeError):
3514 setattr(ext_inst, 'attr_instance', 6)
3515
3516 explicit_ext_inst = AnnotatedExtensionClass()
3517 with assertRaises(AttributeError):
3518 setattr(explicit_ext_inst, 'attr_instance', 6)
3519
3520 [case testMypycAttrNativeClassDunder]
3521 from mypy_extensions import mypyc_attr
3522 from typing import Generic, Optional, TypeVar
3523
3524 _T = TypeVar("_T")
3525
3526 get_count = set_count = del_count = 0
3527
3528 @mypyc_attr(native_class=False)
3529 class Bar(Generic[_T]):
3530 # Note the lack of __deletable__
3531 def __init__(self) -> None:
3532 self.value: str = 'start'
3533 def __get__(self, instance: _T, owner: Optional[type[_T]] = None) -> str:
3534 global get_count
3535 get_count += 1
3536 return self.value
3537 def __set__(self, instance: _T, value: str) -> None:
3538 global set_count
3539 set_count += 1
3540 self.value = value
3541 def __delete__(self, instance: _T) -> None:
3542 global del_count
3543 del_count += 1
3544 del self.value
3545
3546 @mypyc_attr(native_class=False)
3547 class Foo(object):
3548 bar: Bar = Bar()
3549
3550 [file driver.py]
3551 import native
3552
3553 f = native.Foo()
3554 assert(hasattr(f, 'bar'))
3555 assert(native.get_count == 1)
3556 assert(f.bar == 'start')
3557 assert(native.get_count == 2)
3558 f.bar = 'test'
3559 assert(f.bar == 'test')
3560 assert(native.set_count == 1)
3561 del f.bar
3562 assert(not hasattr(f, 'bar'))
3563 assert(native.del_count == 1)
3564
3565 [case testMypycAttrNativeClassMeta]
3566 from mypy_extensions import mypyc_attr
3567 from typing import ClassVar, TypeVar
3568
3569 _T = TypeVar("_T")
3570
3571 @mypyc_attr(native_class=False)
3572 class M(type):
3573 count: ClassVar[int] = 0
3574 def make(cls: type[_T]) -> _T:
3575 M.count += 1
3576 return cls()
3577
3578 # implicit native_class=False
3579 # see testMypycAttrNativeClassMetaError for when trying to set it True
3580 class A(metaclass=M):
3581 pass
3582
3583 [file driver.py]
3584 import native
3585
3586 a: native.A = native.A.make()
3587 assert(native.A.count == 1)
3588
3589 class B(native.A):
3590 pass
3591
3592 b: B = B.make()
3593 assert(B.count == 2)
3594
3595 [case testTypeVarNarrowing]
3596 from typing import TypeVar
3597
3598 class B:
3599 def __init__(self, x: int) -> None:
3600 self.x = x
3601 class C(B):
3602 def __init__(self, x: int, y: str) -> None:
3603 self.x = x
3604 self.y = y
3605
3606 T = TypeVar("T", bound=B)
3607 def f(x: T) -> T:
3608 if isinstance(x, C):
3609 print("C", x.y)
3610 return x
3611 print("B", x.x)
3612 return x
3613
3614 [file driver.py]
3615 from native import f, B, C
3616
3617 f(B(1))
3618 f(C(1, "yes"))
3619 [out]
3620 B 1
3621 C yes
3622
3623 [case testTypeObjectName]
3624 from typing import Any
3625 import re
3626
3627 from dynamic import E, foo, Thing
3628
3629 class C: pass
3630 class D(C): pass
3631
3632 def type_name(t: type[object]) -> str:
3633 return t.__name__
3634
3635 def any_name(x: Any) -> str:
3636 return x.__name__
3637
3638 def assert_type_name(x: Any) -> None:
3639 assert type_name(x) == getattr(x, "__name__")
3640 assert any_name(x) == getattr(x, "__name__")
3641
3642 def assert_any_name(x: Any) -> None:
3643 assert any_name(x) == getattr(x, "__name__")
3644
3645 def test_type_name() -> None:
3646 assert_type_name(C)
3647 assert_type_name(D)
3648 assert_type_name(int)
3649 assert_type_name(E)
3650 assert_type_name(re.Pattern)
3651
3652 def test_module_name() -> None:
3653 assert_any_name(re)
3654
3655 def test_function_name() -> None:
3656 assert_any_name(any_name)
3657 assert_any_name(foo)
3658
3659 def test_obj_name() -> None:
3660 assert_any_name(Thing())
3661
3662 [file dynamic.py]
3663 class E: pass
3664
3665 def foo(): pass
3666
3667 class Thing:
3668 def __init__(self):
3669 self.__name__ = "xyz"
3670
3671 [case testTypeOfObject]
3672 from typing import Any
3673
3674 from dynamic import Dyn
3675
3676 class Foo: pass
3677 class Bar(Foo): pass
3678
3679 def generic_type(x) -> type[object]:
3680 return x.__class__
3681
3682 def test_built_in_type() -> None:
3683 i: Any = int
3684 l: Any = list
3685 assert type(i()) is i().__class__
3686 assert type(i()) is int
3687 assert type(l()) is list
3688 n = 5
3689 assert n.__class__ is i
3690
3691 def test_native_class() -> None:
3692 f_any: Any = Foo()
3693 b_any: Any = Bar()
3694 f: Foo = f_any
3695 b: Foo = b_any
3696 if int("1"): # use int("1") to avoid constant folding
3697 assert type(f) is Foo
3698 assert type(b) is Bar
3699 if int("2"):
3700 assert f.__class__ is Foo
3701 assert b.__class__ is Bar
3702 if int("3"):
3703 assert f_any.__class__ is Foo
3704 assert b_any.__class__ is Bar
3705 if int("4"):
3706 assert type(f_any) is Foo
3707 assert type(b_any) is Bar
3708
3709 def test_python_class() -> None:
3710 d = Dyn()
3711 assert type(d) is Dyn
3712 assert d.__class__ is Dyn
3713
3714 [file dynamic.py]
3715 class Dyn: pass
3716
3717 [case testDunderNew]
3718 from __future__ import annotations
3719 from typing import Any, Union
3720
3721 from testutil import assertRaises
3722
3723 class Add:
3724 l: IntLike
3725 r: IntLike
3726
3727 def __new__(cls, l: IntLike, r: IntLike) -> Any:
3728 return (
3729 l if r == 0 else
3730 r if l == 0 else
3731 super().__new__(cls)
3732 )
3733
3734 def __init__(self, l: IntLike, r: IntLike):
3735 self.l = l
3736 self.r = r
3737
3738 IntLike = Union[int, Add]
3739
3740 class RaisesException:
3741 def __new__(cls, val: int) -> RaisesException:
3742 if val == 0:
3743 raise RuntimeError("Invalid value!")
3744 return super().__new__(cls)
3745
3746 def __init__(self, val: int) -> None:
3747 self.val = val
3748
3749 class ClsArgNotPassed:
3750 def __new__(cls) -> Any:
3751 return super().__new__(str)
3752
3753 def test_dunder_new() -> None:
3754 add_instance: Any = Add(1, 5)
3755 assert type(add_instance) == Add
3756 assert add_instance.l == 1
3757 assert add_instance.r == 5
3758
3759 # TODO: explicit types should not be needed but mypy does not use
3760 # the return type of __new__ which makes mypyc add casts to Add.
3761 right_int: Any = Add(0, 5)
3762 assert type(right_int) == int
3763 assert right_int == 5
3764
3765 left_int: Any = Add(1, 0)
3766 assert type(left_int) == int
3767 assert left_int == 1
3768
3769 with assertRaises(RuntimeError, "Invalid value!"):
3770 raised = RaisesException(0)
3771
3772 not_raised = RaisesException(1)
3773 assert not_raised.val == 1
3774
3775 with assertRaises(TypeError, "object.__new__(str) is not safe, use str.__new__()"):
3776 str_as_cls = ClsArgNotPassed()
3777
3778
3779 [case testDunderNewInInterpreted]
3780 from __future__ import annotations
3781 from typing import Any, Union
3782
3783 class Add:
3784 l: IntLike
3785 r: IntLike
3786
3787 def __new__(cls, l: IntLike, r: IntLike) -> Any:
3788 print(f'running __new__ with {l} and {r}')
3789
3790 return (
3791 l if r == 0 else
3792 r if l == 0 else
3793 super().__new__(cls)
3794 )
3795
3796 def __init__(self, l: IntLike, r: IntLike):
3797 self.l = l
3798 self.r = r
3799
3800 def __repr__(self) -> str:
3801 return f'({self.l} + {self.r})'
3802
3803 IntLike = Union[int, Add]
3804
3805 class RaisesException:
3806 def __new__(cls, val: int) -> RaisesException:
3807 if val == 0:
3808 raise RuntimeError("Invalid value!")
3809 return super().__new__(cls)
3810
3811 def __init__(self, val: int) -> None:
3812 self.val = val
3813
3814 class ClsArgNotPassed:
3815 def __new__(cls) -> Any:
3816 return super().__new__(str)
3817
3818 [file driver.py]
3819 from native import Add, ClsArgNotPassed, RaisesException
3820
3821 from testutil import assertRaises
3822
3823 print(f'{Add(1, 5)=}')
3824 print(f'{Add(0, 5)=}')
3825 print(f'{Add(1, 0)=}')
3826
3827 with assertRaises(RuntimeError, "Invalid value!"):
3828 raised = RaisesException(0)
3829
3830 not_raised = RaisesException(1)
3831 assert not_raised.val == 1
3832
3833 with assertRaises(TypeError, "object.__new__(str) is not safe, use str.__new__()"):
3834 str_as_cls = ClsArgNotPassed()
3835
3836 [out]
3837 running __new__ with 1 and 5
3838 Add(1, 5)=(1 + 5)
3839 running __new__ with 0 and 5
3840 Add(0, 5)=5
3841 running __new__ with 1 and 0
3842 Add(1, 0)=1
3843
3844 [case testObjectDunderNew]
3845 from __future__ import annotations
3846 from typing import Any, Union
3847
3848 from testutil import assertRaises
3849
3850 class Add:
3851 l: IntLike
3852 r: IntLike
3853
3854 def __new__(cls, l: IntLike, r: IntLike) -> Any:
3855 return (
3856 l if r == 0 else
3857 r if l == 0 else
3858 object.__new__(cls)
3859 )
3860
3861 def __init__(self, l: IntLike, r: IntLike):
3862 self.l = l
3863 self.r = r
3864
3865 IntLike = Union[int, Add]
3866
3867 class RaisesException:
3868 def __new__(cls, val: int) -> RaisesException:
3869 if val == 0:
3870 raise RuntimeError("Invalid value!")
3871 return object.__new__(cls)
3872
3873 def __init__(self, val: int) -> None:
3874 self.val = val
3875
3876 class ClsArgNotPassed:
3877 def __new__(cls) -> Any:
3878 return object.__new__(str)
3879
3880 class SkipsBase(Add):
3881 def __new__(cls) -> Any:
3882 obj = object.__new__(cls)
3883 obj.l = 0
3884 obj.r = 0
3885 return obj
3886
3887 def test_dunder_new() -> None:
3888 add_instance: Any = Add(1, 5)
3889 assert type(add_instance) == Add
3890 assert add_instance.l == 1
3891 assert add_instance.r == 5
3892
3893 # TODO: explicit types should not be needed but mypy does not use
3894 # the return type of __new__ which makes mypyc add casts to Add.
3895 right_int: Any = Add(0, 5)
3896 assert type(right_int) == int
3897 assert right_int == 5
3898
3899 left_int: Any = Add(1, 0)
3900 assert type(left_int) == int
3901 assert left_int == 1
3902
3903 with assertRaises(RuntimeError, "Invalid value!"):
3904 _ = RaisesException(0)
3905
3906 not_raised = RaisesException(1)
3907 assert not_raised.val == 1
3908
3909 with assertRaises(TypeError, "object.__new__(str) is not safe, use str.__new__()"):
3910 _ = ClsArgNotPassed()
3911
3912 skip = SkipsBase.__new__(SkipsBase)
3913 assert type(skip) == SkipsBase
3914 assert skip.l == 0
3915 assert skip.r == 0
3916
3917 [case testObjectDunderNewInInterpreted]
3918 from __future__ import annotations
3919 from typing import Any, Union
3920
3921 class Add:
3922 l: IntLike
3923 r: IntLike
3924
3925 def __new__(cls, l: IntLike, r: IntLike) -> Any:
3926 print(f'running __new__ with {l} and {r}')
3927
3928 return (
3929 l if r == 0 else
3930 r if l == 0 else
3931 object.__new__(cls)
3932 )
3933
3934 def __init__(self, l: IntLike, r: IntLike):
3935 self.l = l
3936 self.r = r
3937
3938 def __repr__(self) -> str:
3939 return f'({self.l} + {self.r})'
3940
3941 IntLike = Union[int, Add]
3942
3943 class RaisesException:
3944 def __new__(cls, val: int) -> RaisesException:
3945 if val == 0:
3946 raise RuntimeError("Invalid value!")
3947 return object.__new__(cls)
3948
3949 def __init__(self, val: int) -> None:
3950 self.val = val
3951
3952 class ClsArgNotPassed:
3953 def __new__(cls) -> Any:
3954 return object.__new__(str)
3955
3956 class SkipsBase(Add):
3957 def __new__(cls) -> Any:
3958 obj = object.__new__(cls)
3959 obj.l = 0
3960 obj.r = 0
3961 return obj
3962
3963 [file driver.py]
3964 from native import Add, ClsArgNotPassed, RaisesException, SkipsBase
3965
3966 from testutil import assertRaises
3967
3968 print(f'{Add(1, 5)=}')
3969 print(f'{Add(0, 5)=}')
3970 print(f'{Add(1, 0)=}')
3971
3972 with assertRaises(RuntimeError, "Invalid value!"):
3973 raised = RaisesException(0)
3974
3975 not_raised = RaisesException(1)
3976 assert not_raised.val == 1
3977
3978 with assertRaises(TypeError, "object.__new__(str) is not safe, use str.__new__()"):
3979 str_as_cls = ClsArgNotPassed()
3980
3981 skip = SkipsBase.__new__(SkipsBase)
3982 assert type(skip) == SkipsBase
3983 assert skip.l == 0
3984 assert skip.r == 0
3985
3986 [out]
3987 running __new__ with 1 and 5
3988 Add(1, 5)=(1 + 5)
3989 running __new__ with 0 and 5
3990 Add(0, 5)=5
3991 running __new__ with 1 and 0
3992 Add(1, 0)=1
3993
3994 [case testInheritedDunderNew]
3995 from __future__ import annotations
3996 from mypy_extensions import mypyc_attr
3997 from testutil import assertRaises
3998 from typing_extensions import Self
3999
4000 from m import interpreted_subclass
4001
4002 @mypyc_attr(allow_interpreted_subclasses=True)
4003 class Base:
4004 val: int
4005
4006 def __new__(cls, val: int) -> Self:
4007 obj = super().__new__(cls)
4008 obj.val = val + 1
4009 return obj
4010
4011 def __init__(self, val: int) -> None:
4012 self.init_val = val
4013
4014 def method(self) -> int:
4015 raise NotImplementedError
4016
4017 class Sub(Base):
4018
4019 def __new__(cls, val: int) -> Self:
4020 return super().__new__(cls, val + 1)
4021
4022 def __init__(self, val: int) -> None:
4023 super().__init__(val)
4024 self.init_val = self.init_val * 2
4025
4026 def method(self) -> int:
4027 return 0
4028
4029 class SubWithoutNew(Base):
4030 sub_only_str = ""
4031 sub_only_int: int
4032
4033 def __init__(self, val: int) -> None:
4034 super().__init__(val)
4035 self.init_val = self.init_val * 2
4036
4037 def method(self) -> int:
4038 return 1
4039
4040 class BaseWithoutInterpretedSubclasses:
4041 val: int
4042
4043 def __new__(cls, val: int) -> Self:
4044 obj = super().__new__(cls)
4045 obj.val = val + 1
4046 return obj
4047
4048 def __init__(self, val: int) -> None:
4049 self.init_val = val
4050
4051 def method(self) -> int:
4052 raise NotImplementedError
4053
4054 class SubNoInterpreted(BaseWithoutInterpretedSubclasses):
4055 def __new__(cls, val: int) -> Self:
4056 return super().__new__(cls, val + 1)
4057
4058 def __init__(self, val: int) -> None:
4059 super().__init__(val)
4060 self.init_val = self.init_val * 2
4061
4062 def method(self) -> int:
4063 return 0
4064
4065 class SubNoInterpretedWithoutNew(BaseWithoutInterpretedSubclasses):
4066 def __init__(self, val: int) -> None:
4067 super().__init__(val)
4068 self.init_val = self.init_val * 2
4069
4070 def method(self) -> int:
4071 return 1
4072
4073 def test_inherited_dunder_new() -> None:
4074 b = Base(42)
4075 assert type(b) == Base
4076 assert b.val == 43
4077 assert b.init_val == 42
4078 with assertRaises(NotImplementedError):
4079 b.method()
4080
4081 s = Sub(42)
4082 assert type(s) == Sub
4083 assert s.val == 44
4084 assert s.init_val == 84
4085 assert s.method() == 0
4086
4087 s2 = SubWithoutNew(42)
4088 assert type(s2) == SubWithoutNew
4089 assert s2.val == 43
4090 assert s2.init_val == 84
4091 assert s2.method() == 1
4092 assert s2.sub_only_str == ""
4093 with assertRaises(AttributeError):
4094 s2.sub_only_int
4095 s2.sub_only_int = 11
4096 assert s2.sub_only_int == 11
4097
4098 def test_inherited_dunder_new_without_interpreted_subclasses() -> None:
4099 b = BaseWithoutInterpretedSubclasses(42)
4100 assert type(b) == BaseWithoutInterpretedSubclasses
4101 assert b.val == 43
4102 assert b.init_val == 42
4103 with assertRaises(NotImplementedError):
4104 b.method()
4105
4106 s = SubNoInterpreted(42)
4107 assert type(s) == SubNoInterpreted
4108 assert s.val == 44
4109 assert s.init_val == 84
4110 assert s.method() == 0
4111
4112 s2 = SubNoInterpretedWithoutNew(42)
4113 assert type(s2) == SubNoInterpretedWithoutNew
4114 assert s2.val == 43
4115 assert s2.init_val == 84
4116 assert s2.method() == 1
4117
4118 def test_interpreted_subclass() -> None:
4119 interpreted_subclass(Base)
4120
4121 [file m.py]
4122 from __future__ import annotations
4123 from testutil import assertRaises
4124 from typing_extensions import Self
4125
4126 def interpreted_subclass(base) -> None:
4127 b = base(42)
4128 assert type(b) == base
4129 assert b.val == 43
4130 assert b.init_val == 42
4131 with assertRaises(NotImplementedError):
4132 b.method()
4133
4134 class InterpretedSub(base):
4135 def __new__(cls, val: int) -> Self:
4136 return super().__new__(cls, val + 1)
4137
4138 def __init__(self, val: int) -> None:
4139 super().__init__(val)
4140 self.init_val : int = self.init_val * 2
4141
4142 def method(self) -> int:
4143 return 3
4144
4145 s = InterpretedSub(42)
4146 assert type(s) == InterpretedSub
4147 assert s.val == 44
4148 assert s.init_val == 84
4149 assert s.method() == 3
4150
4151 class InterpretedSubWithoutNew(base):
4152 sub_only_str = ""
4153 sub_only_int: int
4154
4155 def __init__(self, val: int) -> None:
4156 super().__init__(val)
4157 self.init_val : int = self.init_val * 2
4158
4159 def method(self) -> int:
4160 return 4
4161
4162 s2 = InterpretedSubWithoutNew(42)
4163 assert type(s2) == InterpretedSubWithoutNew
4164 assert s2.val == 43
4165 assert s2.init_val == 84
4166 assert s2.method() == 4
4167 assert s2.sub_only_str == ""
4168 with assertRaises(AttributeError):
4169 s2.sub_only_int
4170 s2.sub_only_int = 11
4171 assert s2.sub_only_int == 11
4172
4173 [typing fixtures/typing-full.pyi]
4174
4175 [case testDunderNewInitArgMismatch]
4176 from __future__ import annotations
4177 from testutil import assertRaises
4178
4179 class Test0:
4180 @classmethod
4181 def __new__(cls, val: int = 42) -> Test0:
4182 obj = super().__new__(cls)
4183 obj.val = val
4184 return obj
4185
4186 def __init__(self) -> None:
4187 self.val = 0
4188
4189 class Test1:
4190 def __new__(cls, val: int) -> Test1:
4191 obj = super().__new__(cls)
4192 obj.val = val
4193 return obj
4194
4195 def __init__(self) -> None:
4196 self.val = 0
4197
4198 class Test2:
4199 def __new__(cls) -> Test2:
4200 obj = super().__new__(cls)
4201 return obj
4202
4203 def __init__(self, val: int) -> None:
4204 self.val = val
4205
4206 def test_arg_mismatch() -> None:
4207 t0 = Test0()
4208 assert t0.val == 0
4209 t0 = Test0.__new__(1)
4210 assert t0.val == 1
4211 with assertRaises(TypeError, "__new__() missing required argument 'val'"):
4212 t1 = Test1()
4213 t1 = Test1.__new__(Test1, 2)
4214 assert t1.val == 2
4215 with assertRaises(TypeError, "__new__() takes at most 0 arguments"):
4216 t2 = Test2(42)
4217 t2 = Test2.__new__(Test2)
4218 with assertRaises(AttributeError, "attribute 'val' of 'Test2' undefined"):
4219 print(t2.val)
4220
4221 [case testDunderNewInitArgMismatchInInterpreted]
4222 from __future__ import annotations
4223
4224 class Test0:
4225 # TODO: It should be possible to annotate '@classmethod' here
4226 # but when it's added calling __new__ in interpreted code
4227 # without the explicit type param results in a TypeError.
4228 def __new__(cls, val: int = 42) -> Test0:
4229 obj = super().__new__(cls)
4230 obj.val = val
4231 return obj
4232
4233 def __init__(self) -> None:
4234 self.val = 0
4235
4236 class Test1:
4237 def __new__(cls, val: int) -> Test1:
4238 obj = super().__new__(cls)
4239 obj.val = val
4240 return obj
4241
4242 def __init__(self) -> None:
4243 self.val = 0
4244
4245 class Test2:
4246 def __new__(cls) -> Test2:
4247 obj = super().__new__(cls)
4248 return obj
4249
4250 def __init__(self, val: int) -> None:
4251 self.val = val
4252
4253 [file driver.py]
4254 from native import Test0, Test1, Test2
4255 from testutil import assertRaises
4256
4257 t0 = Test0()
4258 assert t0.val == 0
4259 t0 = Test0.__new__(Test0, 1)
4260 assert t0.val == 1
4261 with assertRaises(TypeError, "__new__() missing required argument 'val'"):
4262 t1 = Test1()
4263 t1 = Test1.__new__(Test1, 2)
4264 assert t1.val == 2
4265 with assertRaises(TypeError, "__new__() takes at most 0 arguments"):
4266 t2 = Test2(42)
4267 t2 = Test2.__new__(Test2)
4268 with assertRaises(AttributeError, "attribute 'val' of 'Test2' undefined"):
4269 print(t2.val)
4270
4271 [case testDunderNewAttributeAccess]
4272 from __future__ import annotations
4273
4274 from mypy_extensions import u8
4275 from testutil import assertRaises
4276
4277 class Test:
4278 native: int
4279 generic: object
4280 bitfield: u8
4281 default: int = 5
4282
4283 def __new__(cls, native: int, generic: object, bitfield: u8) -> Test:
4284 obj = super().__new__(cls)
4285
4286 with assertRaises(AttributeError, "attribute 'native' of 'Test' undefined"):
4287 print(obj.native)
4288 with assertRaises(AttributeError, "attribute 'generic' of 'Test' undefined"):
4289 print(obj.generic)
4290 with assertRaises(AttributeError, "attribute 'bitfield' of 'Test' undefined"):
4291 print(obj.bitfield)
4292
4293 obj.native = native
4294 obj.generic = generic
4295 obj.bitfield = bitfield
4296
4297 obj.native = obj.native + 1
4298 obj.generic = obj.generic.__str__()
4299 obj.bitfield = obj.bitfield & 0x0F
4300 obj.default = obj.default * 2
4301 return obj
4302
4303 def test_attribute_access() -> None:
4304 t = Test(42, {}, 0xCC)
4305 assert t.native == 43
4306 assert t.generic == "{}"
4307 assert t.bitfield == 0x0C
4308 assert t.default == 10
4309
4310 [case testDunderNewAttributeAccessInInterpreted]
4311 from __future__ import annotations
4312
4313 from mypy_extensions import u8
4314 from testutil import assertRaises
4315
4316 class Test:
4317 native: int
4318 generic: object
4319 bitfield: u8
4320 default: int = 5
4321
4322 def __new__(cls, native: int, generic: object, bitfield: u8) -> Test:
4323 obj = super().__new__(cls)
4324
4325 with assertRaises(AttributeError, "attribute 'native' of 'Test' undefined"):
4326 print(obj.native)
4327 with assertRaises(AttributeError, "attribute 'generic' of 'Test' undefined"):
4328 print(obj.generic)
4329 with assertRaises(AttributeError, "attribute 'bitfield' of 'Test' undefined"):
4330 print(obj.bitfield)
4331
4332 obj.native = native
4333 obj.generic = generic
4334 obj.bitfield = bitfield
4335
4336 obj.native = obj.native + 1
4337 obj.generic = obj.generic.__str__()
4338 obj.bitfield = obj.bitfield & 0x0F
4339 obj.default = obj.default * 2
4340 return obj
4341
4342 [file driver.py]
4343 from native import Test
4344
4345 t = Test(42, {}, 0xCC)
4346 assert t.native == 43
4347 assert t.generic == "{}"
4348 assert t.bitfield == 0x0C
4349 assert t.default == 10
4350
4351 [case testUntransformedDunderNewCalls]
4352 from testutil import assertRaises
4353 from typing import Any
4354
4355 class TestStrCls:
4356 def __new__(cls):
4357 return str.__new__(cls)
4358
4359 @classmethod
4360 def factory(cls):
4361 return str.__new__(cls)
4362
4363 class TestStrStr:
4364 def __new__(cls):
4365 return str.__new__(str)
4366
4367 @classmethod
4368 def factory(cls):
4369 return str.__new__(str)
4370
4371 class TestStrInt:
4372 def __new__(cls):
4373 return str.__new__(int)
4374
4375 @classmethod
4376 def factory(cls):
4377 return str.__new__(int)
4378
4379 def test_untransformed_dunder_new() -> None:
4380 with assertRaises(TypeError, "str.__new__(TestStrCls): TestStrCls is not a subtype of str"):
4381 i = TestStrCls()
4382
4383 j: Any = TestStrStr()
4384 assert j == ""
4385
4386 with assertRaises(TypeError, "str.__new__(int): int is not a subtype of str"):
4387 k = TestStrInt()
4388
4389 with assertRaises(TypeError, "str.__new__(TestStrCls): TestStrCls is not a subtype of str"):
4390 i = TestStrCls.factory()
4391
4392 j = TestStrStr.factory()
4393 assert j == ""
4394
4395 with assertRaises(TypeError, "str.__new__(int): int is not a subtype of str"):
4396 k = TestStrInt.factory()
4397
4398 [case testPerTypeFreeList]
4399 from __future__ import annotations
4400
4401 from mypy_extensions import mypyc_attr
4402
4403 a: list[int] = []
4404
4405 @mypyc_attr(free_list_len=1)
4406 class Foo:
4407 def __init__(self, x: int) -> None:
4408 self.x = x
4409 a.append(x)
4410
4411 def test_alloc() -> None:
4412 x: Foo | None
4413 y: Foo | None
4414
4415 x = Foo(1)
4416 assert x.x == 1
4417 x = None
4418
4419 x = Foo(2)
4420 assert x.x == 2
4421 y = Foo(3)
4422 assert x.x == 2
4423 assert y.x == 3
4424 x = None
4425 y = None
4426 assert a == [1, 2, 3]
4427
4428 x = Foo(4)
4429 assert x.x == 4
4430 y = Foo(5)
4431 assert x.x == 4
4432 assert y.x == 5
4433
4434 @mypyc_attr(free_list_len=1)
4435 class Base:
4436 def __init__(self, x: str) -> None:
4437 self.x = x
4438
4439 class Deriv(Base):
4440 def __init__(self, x: str, y: str) -> None:
4441 super().__init__(x)
4442 self.y = y
4443
4444 @mypyc_attr(free_list_len=1)
4445 class Deriv2(Base):
4446 def __init__(self, x: str, y: str) -> None:
4447 super().__init__(x)
4448 self.y = y
4449
4450 def test_inheritance() -> None:
4451 x: Base | None
4452 y: Base | None
4453 x = Base('x' + str())
4454 y = Base('y' + str())
4455 y = None
4456 d = Deriv('a' + str(), 'b' + str())
4457 assert type(d) is Deriv
4458 assert d.x == 'a'
4459 assert d.y == 'b'
4460 assert x.x == 'x'
4461 y = Base('z' + str())
4462 assert d.x == 'a'
4463 assert d.y == 'b'
4464 assert y.x == 'z'
4465 x = None
4466 y = None
4467
4468 def test_inheritance_2() -> None:
4469 x: Base | None
4470 y: Base | None
4471 d: Deriv2 | None
4472 x = Base('x' + str())
4473 y = Base('y' + str())
4474 y = None
4475 d = Deriv2('a' + str(), 'b' + str())
4476 assert type(d) is Deriv2
4477 assert d.x == 'a'
4478 assert d.y == 'b'
4479 assert x.x == 'x'
4480 d = None
4481 d = Deriv2('c' + str(), 'd' + str())
4482 assert type(d) is Deriv2
4483 assert d.x == 'c'
4484 assert d.y == 'd'
4485 assert x.x == 'x'
4486 y = Base('z' + str())
4487 assert type(y) is Base
4488 assert d.x == 'c'
4489 assert d.y == 'd'
4490 assert y.x == 'z'
4491 x = None
4492 y = None
4493 d = None
4494
4495 [case testDunderGetAttr]
4496 from mypy_extensions import mypyc_attr
4497 from typing import ClassVar
4498
4499 class GetAttr:
4500 class_var = "x"
4501
4502 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4503 self.extra_attrs = extra_attrs
4504 self.regular_attr = regular_attr
4505
4506 def __getattr__(self, attr: str) -> object:
4507 return self.extra_attrs.get(attr)
4508
4509 class GetAttrDefault:
4510 class_var: ClassVar[str] = "x"
4511
4512 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4513 self.extra_attrs = extra_attrs
4514 self.regular_attr = regular_attr
4515
4516 def __getattr__(self, attr: str, default: int = 8, mult: int = 1) -> object:
4517 return self.extra_attrs.get(attr, default * mult)
4518
4519 class GetAttrInherited(GetAttr):
4520 subclass_var = "y"
4521
4522 def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):
4523 super().__init__(extra_attrs, regular_attr)
4524 self.sub_attr = sub_attr
4525
4526 class GetAttrOverridden(GetAttr):
4527 subclass_var: ClassVar[str] = "y"
4528
4529 def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):
4530 super().__init__(extra_attrs, regular_attr)
4531 self.sub_attr = sub_attr
4532
4533 def __getattr__(self, attr: str) -> str:
4534 return attr
4535
4536 @mypyc_attr(native_class=False)
4537 class GetAttrNonNative:
4538 class_var = "x"
4539
4540 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4541 self.extra_attrs = extra_attrs
4542 self.regular_attr = regular_attr
4543
4544 def __getattr__(self, attr: str) -> object:
4545 return self.extra_attrs.get(attr)
4546
4547 def test_getattr() -> None:
4548 i = GetAttr({"one": 1, "two": "two", "three": 3.14}, 42)
4549 assert i.__getattr__("one") == 1
4550 assert i.__getattr__("regular_attr") == None
4551 assert i.__getattr__("class_var") == None
4552 assert i.__getattr__("four") == None
4553
4554 assert getattr(i, "two") == "two"
4555 assert getattr(i, "regular_attr") == 42
4556 assert getattr(i, "class_var") == "x"
4557 assert getattr(i, "four") == None
4558
4559 assert i.three == 3.14
4560 assert i.regular_attr == 42
4561 assert i.class_var == "x"
4562 assert i.four == None
4563
4564 assert i.__class__ == GetAttr
4565
4566 i.extra_attrs["regular_attr"] = (4, 4, 4)
4567 assert i.__getattr__("regular_attr") == (4, 4, 4)
4568 assert getattr(i, "regular_attr") == 42
4569 assert i.regular_attr == 42
4570
4571 def test_getattr_default() -> None:
4572 i = GetAttrDefault({"one": 1, "two": "two", "three": 3.14}, 42)
4573 assert i.__getattr__("one") == 1
4574 assert i.__getattr__("regular_attr") == 8
4575 assert i.__getattr__("class_var") == 8
4576 assert i.__getattr__("four", 4, 3) == 12
4577
4578 assert getattr(i, "two") == "two"
4579 assert getattr(i, "regular_attr") == 42
4580 assert getattr(i, "class_var") == "x"
4581 assert getattr(i, "four") == 8
4582
4583 assert i.three == 3.14
4584 assert i.regular_attr == 42
4585 assert i.class_var == "x"
4586 assert i.four == 8
4587
4588 assert i.__class__ == GetAttrDefault
4589
4590 i.extra_attrs["class_var"] = (4, 4, 4)
4591 assert i.__getattr__("class_var") == (4, 4, 4)
4592 assert getattr(i, "class_var") == "x"
4593 assert i.class_var == "x"
4594
4595 def test_getattr_inherited() -> None:
4596 i = GetAttrInherited({"one": 1, "two": "two", "three": 3.14}, 42, 24)
4597 assert i.__getattr__("one") == 1
4598 assert i.__getattr__("regular_attr") == None
4599 assert i.__getattr__("sub_attr") == None
4600 assert i.__getattr__("class_var") == None
4601 assert i.__getattr__("subclass_var") == None
4602 assert i.__getattr__("four") == None
4603
4604 assert getattr(i, "two") == "two"
4605 assert getattr(i, "regular_attr") == 42
4606 assert getattr(i, "sub_attr") == 24
4607 assert getattr(i, "class_var") == "x"
4608 assert getattr(i, "subclass_var") == "y"
4609 assert getattr(i, "four") == None
4610
4611 assert i.three == 3.14
4612 assert i.regular_attr == 42
4613 assert i.sub_attr == 24
4614 assert i.class_var == "x"
4615 assert i.subclass_var == "y"
4616 assert i.four == None
4617
4618 assert i.__class__ == GetAttrInherited
4619
4620 i.extra_attrs["sub_attr"] = (4, 4, 4)
4621 assert i.__getattr__("sub_attr") == (4, 4, 4)
4622 assert getattr(i, "sub_attr") == 24
4623 assert i.sub_attr == 24
4624
4625 base_ref: GetAttr = i
4626 assert getattr(base_ref, "sub_attr") == 24
4627 assert base_ref.sub_attr == 24
4628
4629 assert getattr(base_ref, "subclass_var") == "y"
4630 assert base_ref.subclass_var == "y"
4631
4632 assert getattr(base_ref, "new") == None
4633 assert base_ref.new == None
4634
4635 assert base_ref.__class__ == GetAttrInherited
4636
4637
4638 def test_getattr_overridden() -> None:
4639 i = GetAttrOverridden({"one": 1, "two": "two", "three": 3.14}, 42, 24)
4640 assert i.__getattr__("one") == "one"
4641 assert i.__getattr__("regular_attr") == "regular_attr"
4642 assert i.__getattr__("sub_attr") == "sub_attr"
4643 assert i.__getattr__("class_var") == "class_var"
4644 assert i.__getattr__("subclass_var") == "subclass_var"
4645 assert i.__getattr__("four") == "four"
4646
4647 assert getattr(i, "two") == "two"
4648 assert getattr(i, "regular_attr") == 42
4649 assert getattr(i, "sub_attr") == 24
4650 assert getattr(i, "class_var") == "x"
4651 assert getattr(i, "subclass_var") == "y"
4652 assert getattr(i, "four") == "four"
4653
4654 assert i.three == "three"
4655 assert i.regular_attr == 42
4656 assert i.sub_attr == 24
4657 assert i.class_var == "x"
4658 assert i.subclass_var == "y"
4659 assert i.four == "four"
4660
4661 assert i.__class__ == GetAttrOverridden
4662
4663 i.extra_attrs["subclass_var"] = (4, 4, 4)
4664 assert i.__getattr__("subclass_var") == "subclass_var"
4665 assert getattr(i, "subclass_var") == "y"
4666 assert i.subclass_var == "y"
4667
4668 base_ref: GetAttr = i
4669 assert getattr(base_ref, "sub_attr") == 24
4670 assert base_ref.sub_attr == 24
4671
4672 assert getattr(base_ref, "subclass_var") == "y"
4673 assert base_ref.subclass_var == "y"
4674
4675 assert getattr(base_ref, "new") == "new"
4676 assert base_ref.new == "new"
4677
4678 assert base_ref.__class__ == GetAttrOverridden
4679
4680 def test_getattr_nonnative() -> None:
4681 i = GetAttr({"one": 1, "two": "two", "three": 3.14}, 42)
4682 assert i.__getattr__("one") == 1
4683 assert i.__getattr__("regular_attr") == None
4684 assert i.__getattr__("class_var") == None
4685 assert i.__getattr__("four") == None
4686
4687 assert getattr(i, "two") == "two"
4688 assert getattr(i, "regular_attr") == 42
4689 assert getattr(i, "class_var") == "x"
4690 assert getattr(i, "four") == None
4691
4692 assert i.three == 3.14
4693 assert i.regular_attr == 42
4694 assert i.class_var == "x"
4695 assert i.four == None
4696
4697 assert i.__class__ == GetAttr
4698
4699 i.extra_attrs["regular_attr"] = (4, 4, 4)
4700 assert i.__getattr__("regular_attr") == (4, 4, 4)
4701 assert getattr(i, "regular_attr") == 42
4702 assert i.regular_attr == 42
4703
4704 [typing fixtures/typing-full.pyi]
4705
4706 [case testDunderGetAttrInterpreted]
4707 from mypy_extensions import mypyc_attr
4708 from typing import ClassVar
4709
4710 class GetAttr:
4711 class_var = "x"
4712
4713 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4714 self.extra_attrs = extra_attrs
4715 self.regular_attr = regular_attr
4716
4717 def __getattr__(self, attr: str) -> object:
4718 return self.extra_attrs.get(attr)
4719
4720 class GetAttrDefault:
4721 class_var: ClassVar[str] = "x"
4722
4723 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4724 self.extra_attrs = extra_attrs
4725 self.regular_attr = regular_attr
4726
4727 def __getattr__(self, attr: str, default: int = 8, mult: int = 1) -> object:
4728 return self.extra_attrs.get(attr, default * mult)
4729
4730 class GetAttrInherited(GetAttr):
4731 subclass_var = "y"
4732
4733 def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):
4734 super().__init__(extra_attrs, regular_attr)
4735 self.sub_attr = sub_attr
4736
4737 class GetAttrOverridden(GetAttr):
4738 subclass_var: ClassVar[str] = "y"
4739
4740 def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):
4741 super().__init__(extra_attrs, regular_attr)
4742 self.sub_attr = sub_attr
4743
4744 def __getattr__(self, attr: str) -> str:
4745 return attr
4746
4747 @mypyc_attr(native_class=False)
4748 class GetAttrNonNative:
4749 class_var = "x"
4750
4751 def __init__(self, extra_attrs: dict[str, object], regular_attr: int):
4752 self.extra_attrs = extra_attrs
4753 self.regular_attr = regular_attr
4754
4755 def __getattr__(self, attr: str) -> object:
4756 return self.extra_attrs.get(attr)
4757
4758 [file driver.py]
4759 from native import GetAttr, GetAttrDefault, GetAttrInherited, GetAttrOverridden, GetAttrNonNative
4760
4761 def test_getattr() -> None:
4762 i = GetAttr({"one": 1, "two": "two", "three": 3.14}, 42)
4763 assert i.__getattr__("one") == 1
4764 assert i.__getattr__("regular_attr") == None
4765 assert i.__getattr__("class_var") == None
4766 assert i.__getattr__("four") == None
4767
4768 assert getattr(i, "two") == "two"
4769 assert getattr(i, "regular_attr") == 42
4770 assert getattr(i, "class_var") == "x"
4771 assert getattr(i, "four") == None
4772
4773 assert i.three == 3.14
4774 assert i.regular_attr == 42
4775 assert i.class_var == "x"
4776 assert i.four == None
4777
4778 assert i.__class__ == GetAttr
4779
4780 i.extra_attrs["regular_attr"] = (4, 4, 4)
4781 assert i.__getattr__("regular_attr") == (4, 4, 4)
4782 assert getattr(i, "regular_attr") == 42
4783 assert i.regular_attr == 42
4784
4785 def test_getattr_default() -> None:
4786 i = GetAttrDefault({"one": 1, "two": "two", "three": 3.14}, 42)
4787 assert i.__getattr__("one") == 1
4788 assert i.__getattr__("regular_attr") == 8
4789 assert i.__getattr__("class_var") == 8
4790 assert i.__getattr__("four", 4, 3) == 12
4791
4792 assert getattr(i, "two") == "two"
4793 assert getattr(i, "regular_attr") == 42
4794 assert getattr(i, "class_var") == "x"
4795 assert getattr(i, "four") == 8
4796
4797 assert i.three == 3.14
4798 assert i.regular_attr == 42
4799 assert i.class_var == "x"
4800 assert i.four == 8
4801
4802 assert i.__class__ == GetAttrDefault
4803
4804 i.extra_attrs["class_var"] = (4, 4, 4)
4805 assert i.__getattr__("class_var") == (4, 4, 4)
4806 assert getattr(i, "class_var") == "x"
4807 assert i.class_var == "x"
4808
4809 def test_getattr_inherited() -> None:
4810 i = GetAttrInherited({"one": 1, "two": "two", "three": 3.14}, 42, 24)
4811 assert i.__getattr__("one") == 1
4812 assert i.__getattr__("regular_attr") == None
4813 assert i.__getattr__("sub_attr") == None
4814 assert i.__getattr__("class_var") == None
4815 assert i.__getattr__("subclass_var") == None
4816 assert i.__getattr__("four") == None
4817
4818 assert getattr(i, "two") == "two"
4819 assert getattr(i, "regular_attr") == 42
4820 assert getattr(i, "sub_attr") == 24
4821 assert getattr(i, "class_var") == "x"
4822 assert getattr(i, "subclass_var") == "y"
4823 assert getattr(i, "four") == None
4824
4825 assert i.three == 3.14
4826 assert i.regular_attr == 42
4827 assert i.sub_attr == 24
4828 assert i.class_var == "x"
4829 assert i.subclass_var == "y"
4830 assert i.four == None
4831
4832 assert i.__class__ == GetAttrInherited
4833
4834 i.extra_attrs["sub_attr"] = (4, 4, 4)
4835 assert i.__getattr__("sub_attr") == (4, 4, 4)
4836 assert getattr(i, "sub_attr") == 24
4837 assert i.sub_attr == 24
4838
4839 base_ref: GetAttr = i
4840 assert getattr(base_ref, "sub_attr") == 24
4841 assert base_ref.sub_attr == 24
4842
4843 assert getattr(base_ref, "subclass_var") == "y"
4844 assert base_ref.subclass_var == "y"
4845
4846 assert getattr(base_ref, "new") == None
4847 assert base_ref.new == None
4848
4849 assert base_ref.__class__ == GetAttrInherited
4850
4851
4852 def test_getattr_overridden() -> None:
4853 i = GetAttrOverridden({"one": 1, "two": "two", "three": 3.14}, 42, 24)
4854 assert i.__getattr__("one") == "one"
4855 assert i.__getattr__("regular_attr") == "regular_attr"
4856 assert i.__getattr__("sub_attr") == "sub_attr"
4857 assert i.__getattr__("class_var") == "class_var"
4858 assert i.__getattr__("subclass_var") == "subclass_var"
4859 assert i.__getattr__("four") == "four"
4860
4861 assert getattr(i, "two") == "two"
4862 assert getattr(i, "regular_attr") == 42
4863 assert getattr(i, "sub_attr") == 24
4864 assert getattr(i, "class_var") == "x"
4865 assert getattr(i, "subclass_var") == "y"
4866 assert getattr(i, "four") == "four"
4867
4868 assert i.three == "three"
4869 assert i.regular_attr == 42
4870 assert i.sub_attr == 24
4871 assert i.class_var == "x"
4872 assert i.subclass_var == "y"
4873 assert i.four == "four"
4874
4875 assert i.__class__ == GetAttrOverridden
4876
4877 i.extra_attrs["subclass_var"] = (4, 4, 4)
4878 assert i.__getattr__("subclass_var") == "subclass_var"
4879 assert getattr(i, "subclass_var") == "y"
4880 assert i.subclass_var == "y"
4881
4882 base_ref: GetAttr = i
4883 assert getattr(base_ref, "sub_attr") == 24
4884 assert base_ref.sub_attr == 24
4885
4886 assert getattr(base_ref, "subclass_var") == "y"
4887 assert base_ref.subclass_var == "y"
4888
4889 assert getattr(base_ref, "new") == "new"
4890 assert base_ref.new == "new"
4891
4892 assert base_ref.__class__ == GetAttrOverridden
4893
4894 def test_getattr_nonnative() -> None:
4895 i = GetAttr({"one": 1, "two": "two", "three": 3.14}, 42)
4896 assert i.__getattr__("one") == 1
4897 assert i.__getattr__("regular_attr") == None
4898 assert i.__getattr__("class_var") == None
4899 assert i.__getattr__("four") == None
4900
4901 assert getattr(i, "two") == "two"
4902 assert getattr(i, "regular_attr") == 42
4903 assert getattr(i, "class_var") == "x"
4904 assert getattr(i, "four") == None
4905
4906 assert i.three == 3.14
4907 assert i.regular_attr == 42
4908 assert i.class_var == "x"
4909 assert i.four == None
4910
4911 assert i.__class__ == GetAttr
4912
4913 i.extra_attrs["regular_attr"] = (4, 4, 4)
4914 assert i.__getattr__("regular_attr") == (4, 4, 4)
4915 assert getattr(i, "regular_attr") == 42
4916 assert i.regular_attr == 42
4917
4918 test_getattr()
4919 test_getattr_default()
4920 test_getattr_inherited()
4921 test_getattr_overridden()
4922 test_getattr_nonnative()
4923
4924 [typing fixtures/typing-full.pyi]
4925
4926 [case testDunderSetAttr]
4927 from mypy_extensions import mypyc_attr
4928 from testutil import assertRaises
4929 from typing import ClassVar
4930
4931 class SetAttr:
4932 _attributes: dict[str, object]
4933 regular_attr: int
4934 class_var: ClassVar[str] = "x"
4935 const: int = 42
4936
4937 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
4938 super().__setattr__("_attributes", extra_attrs)
4939 super().__setattr__("regular_attr", regular_attr)
4940
4941 def __setattr__(self, key: str, val: object) -> None:
4942 if key == "regular_attr":
4943 super().__setattr__("regular_attr", val)
4944 elif key == "class_var" or key == "const":
4945 raise AttributeError()
4946 else:
4947 self._attributes[key] = val
4948
4949 def __getattr__(self, key: str) -> object:
4950 return self._attributes.get(key)
4951
4952 class SetAttrInherited(SetAttr):
4953 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
4954 super().__init__(regular_attr, extra_attrs)
4955
4956 class SetAttrOverridden(SetAttr):
4957 sub_attr: int
4958 subclass_var: ClassVar[str] = "y"
4959
4960 def __init__(self, regular_attr: int, sub_attr: int, extra_attrs: dict[str, object]) -> None:
4961 super().__init__(regular_attr, extra_attrs)
4962 object.__setattr__(self, "sub_attr", sub_attr)
4963
4964 def __setattr__(self, key: str, val: object) -> None:
4965 if key == "sub_attr":
4966 object.__setattr__(self, "sub_attr", val)
4967 elif key == "subclass_var":
4968 raise AttributeError()
4969 else:
4970 super().__setattr__(key, val)
4971
4972 def __delattr__(self, key: str) -> None:
4973 del self._attributes[key]
4974
4975 @mypyc_attr(native_class=False)
4976 class SetAttrNonNative:
4977 _attributes: dict[str, object]
4978 regular_attr: int
4979 class_var: ClassVar[str] = "x"
4980 const: int = 42
4981
4982 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
4983 super().__setattr__("_attributes", extra_attrs)
4984 super().__setattr__("regular_attr", regular_attr)
4985
4986 def __setattr__(self, key: str, val: object) -> None:
4987 if key == "regular_attr":
4988 super().__setattr__("regular_attr", val)
4989 elif key == "class_var" or key == "const":
4990 raise AttributeError()
4991 else:
4992 self._attributes[key] = val
4993
4994 def __getattr__(self, key: str) -> object:
4995 return self._attributes.get(key)
4996
4997 class NoSetAttr:
4998 def __init__(self, attr: int) -> None:
4999 self.attr = attr
5000
5001 def object_setattr(self, attr: str, val: object) -> None:
5002 object.__setattr__(self, attr, val)
5003
5004 def super_setattr(self, attr: str, val: object) -> None:
5005 super().__setattr__(attr, val)
5006
5007 @mypyc_attr(native_class=False)
5008 class NoSetAttrNonNative:
5009 def __init__(self, attr: int) -> None:
5010 self.attr = attr
5011
5012 def object_setattr(self, attr: str, val: object) -> None:
5013 object.__setattr__(self, attr, val)
5014
5015 def super_setattr(self, attr: str, val: object) -> None:
5016 super().__setattr__(attr, val)
5017
5018 def __getattr__(self, attr: str) -> object:
5019 pass
5020
5021 def test_setattr() -> None:
5022 i = SetAttr(99, {"one": 1})
5023 assert i.class_var == "x"
5024 assert i.regular_attr == 99
5025 assert i.one == 1
5026 assert i.two == None
5027 assert i.const == 42
5028 i = i
5029
5030 i.__setattr__("two", "2")
5031 assert i.two == "2"
5032 i.__setattr__("regular_attr", 101)
5033 assert i.regular_attr == 101
5034 with assertRaises(AttributeError):
5035 i.__setattr__("class_var", "y")
5036 with assertRaises(AttributeError):
5037 i.__setattr__("const", 43)
5038
5039 setattr(i, "three", (3,3,3))
5040 assert i.three == (3,3,3)
5041 setattr(i, "regular_attr", 102)
5042 assert i.regular_attr == 102
5043 with assertRaises(AttributeError):
5044 setattr(i, "class_var", "z")
5045 with assertRaises(AttributeError):
5046 setattr(i, "const", 44)
5047
5048 i.four = [4,4]
5049 assert i.four == [4,4]
5050 i.regular_attr = 103
5051 assert i.regular_attr == 103
5052 with assertRaises(AttributeError):
5053 i.const = 45
5054
5055 # Doesn't work because there's no __delattr__.
5056 with assertRaises(AttributeError):
5057 del i.four
5058
5059 def test_setattr_inherited() -> None:
5060 i = SetAttrInherited(99, {"one": 1})
5061 assert i.class_var == "x"
5062 assert i.regular_attr == 99
5063 assert i.one == 1
5064 assert i.two == None
5065 assert i.const == 42
5066 i = i
5067
5068 i.__setattr__("two", "2")
5069 assert i.two == "2"
5070 i.__setattr__("regular_attr", 101)
5071 assert i.regular_attr == 101
5072 with assertRaises(AttributeError):
5073 i.__setattr__("class_var", "y")
5074 with assertRaises(AttributeError):
5075 i.__setattr__("const", 43)
5076
5077 setattr(i, "three", (3,3,3))
5078 assert i.three == (3,3,3)
5079 setattr(i, "regular_attr", 102)
5080 assert i.regular_attr == 102
5081 with assertRaises(AttributeError):
5082 setattr(i, "class_var", "z")
5083 with assertRaises(AttributeError):
5084 setattr(i, "const", 44)
5085
5086 i.four = [4,4]
5087 assert i.four == [4,4]
5088 i.regular_attr = 103
5089 assert i.regular_attr == 103
5090 with assertRaises(AttributeError):
5091 i.const = 45
5092
5093 # Doesn't work because there's no __delattr__.
5094 with assertRaises(AttributeError):
5095 del i.four
5096
5097 def test_setattr_overridden() -> None:
5098 i = SetAttrOverridden(99, 1, {"one": 1})
5099 assert i.class_var == "x"
5100 assert i.subclass_var == "y"
5101 assert i.regular_attr == 99
5102 assert i.sub_attr == 1
5103 assert i.one == 1
5104 assert i.two == None
5105 assert i.const == 42
5106 i = i
5107
5108 i.__setattr__("two", "2")
5109 assert i.two == "2"
5110 i.__setattr__("regular_attr", 101)
5111 assert i.regular_attr == 101
5112 i.__setattr__("sub_attr", 2)
5113 assert i.sub_attr == 2
5114 with assertRaises(AttributeError):
5115 i.__setattr__("class_var", "y")
5116 with assertRaises(AttributeError):
5117 i.__setattr__("subclass_var", "a")
5118 with assertRaises(AttributeError):
5119 i.__setattr__("const", 43)
5120
5121 setattr(i, "three", (3,3,3))
5122 assert i.three == (3,3,3)
5123 setattr(i, "regular_attr", 102)
5124 assert i.regular_attr == 102
5125 setattr(i, "sub_attr", 3)
5126 assert i.sub_attr == 3
5127 with assertRaises(AttributeError):
5128 setattr(i, "class_var", "z")
5129 with assertRaises(AttributeError):
5130 setattr(i, "subclass_var", "b")
5131 with assertRaises(AttributeError):
5132 setattr(i, "const", 44)
5133
5134 i.four = [4,4]
5135 assert i.four == [4,4]
5136 i.regular_attr = 103
5137 assert i.regular_attr == 103
5138 i.sub_attr = 4
5139 assert i.sub_attr == 4
5140 with assertRaises(AttributeError):
5141 i.const = 45
5142
5143 del i.four
5144 assert "four" not in i._attributes
5145
5146 delattr(i, "three")
5147 assert "three" not in i._attributes
5148
5149 i.__delattr__("two")
5150 assert "two" not in i._attributes
5151
5152 base_ref: SetAttr = i
5153 setattr(base_ref, "sub_attr", 5)
5154 assert base_ref.sub_attr == 5
5155
5156 base_ref.sub_attr = 6
5157 assert base_ref.sub_attr == 6
5158
5159 with assertRaises(AttributeError):
5160 setattr(base_ref, "subclass_var", "c")
5161
5162 base_ref.new_attr = "new_attr"
5163 assert base_ref.new_attr == "new_attr"
5164
5165 del base_ref.new_attr
5166 assert "new_attr" not in base_ref._attributes
5167
5168 def test_setattr_nonnative() -> None:
5169 i = SetAttrNonNative(99, {"one": 1})
5170 assert i.class_var == "x"
5171 assert i.regular_attr == 99
5172 assert i.one == 1
5173 assert i.two == None
5174 assert i.const == 42
5175 i = i
5176
5177 i.__setattr__("two", "2")
5178 assert i.two == "2"
5179 i.__setattr__("regular_attr", 101)
5180 assert i.regular_attr == 101
5181 with assertRaises(AttributeError):
5182 i.__setattr__("class_var", "y")
5183 with assertRaises(AttributeError):
5184 i.__setattr__("const", 43)
5185
5186 setattr(i, "three", (3,3,3))
5187 assert i.three == (3,3,3)
5188 setattr(i, "regular_attr", 102)
5189 assert i.regular_attr == 102
5190 with assertRaises(AttributeError):
5191 setattr(i, "class_var", "z")
5192 with assertRaises(AttributeError):
5193 setattr(i, "const", 44)
5194
5195 i.four = [4,4]
5196 assert i.four == [4,4]
5197 i.regular_attr = 103
5198 assert i.regular_attr == 103
5199 with assertRaises(AttributeError):
5200 i.const = 45
5201
5202 # Doesn't work because there's no __delattr__.
5203 with assertRaises(AttributeError):
5204 del i.four
5205
5206 def test_no_setattr() -> None:
5207 i = NoSetAttr(99)
5208 i.super_setattr("attr", 100)
5209 assert i.attr == 100
5210
5211 i.object_setattr("attr", 101)
5212 assert i.attr == 101
5213
5214 object.__setattr__(i, "attr", 102)
5215 assert i.attr == 102
5216
5217 with assertRaises(AttributeError):
5218 i.super_setattr("not_attr", 100)
5219
5220 with assertRaises(AttributeError):
5221 i.object_setattr("not_attr", 101)
5222
5223 with assertRaises(AttributeError):
5224 object.__setattr__(i, "not_attr", 102)
5225
5226 def test_no_setattr_nonnative() -> None:
5227 i = NoSetAttrNonNative(99)
5228 i.super_setattr("attr", 100)
5229 assert i.attr == 100
5230
5231 i.object_setattr("attr", 101)
5232 assert i.attr == 101
5233
5234 object.__setattr__(i, "attr", 102)
5235 assert i.attr == 102
5236
5237 i.super_setattr("one", 100)
5238 assert i.one == 100
5239
5240 i.object_setattr("two", 101)
5241 assert i.two == 101
5242
5243 object.__setattr__(i, "three", 102)
5244 assert i.three == 102
5245
5246 i = i
5247
5248 del i.three
5249 assert i.three == None
5250
5251 delattr(i, "two")
5252 assert i.two == None
5253
5254 object.__delattr__(i, "one")
5255 assert i.one == None
5256
5257 [typing fixtures/typing-full.pyi]
5258
5259 [case testDunderSetAttrInterpreted]
5260 from mypy_extensions import mypyc_attr
5261 from typing import ClassVar
5262
5263 class SetAttr:
5264 _attributes: dict[str, object]
5265 regular_attr: int
5266 class_var: ClassVar[str] = "x"
5267 const: int = 42
5268
5269 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
5270 super().__setattr__("_attributes", extra_attrs)
5271 super().__setattr__("regular_attr", regular_attr)
5272
5273 def __setattr__(self, key: str, val: object) -> None:
5274 if key == "regular_attr":
5275 super().__setattr__("regular_attr", val)
5276 elif key == "class_var" or key == "const":
5277 raise AttributeError()
5278 else:
5279 self._attributes[key] = val
5280
5281 def __getattr__(self, key: str) -> object:
5282 return self._attributes.get(key)
5283
5284 class SetAttrInherited(SetAttr):
5285 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
5286 super().__init__(regular_attr, extra_attrs)
5287
5288 class SetAttrOverridden(SetAttr):
5289 sub_attr: int
5290 subclass_var: ClassVar[str] = "y"
5291
5292 def __init__(self, regular_attr: int, sub_attr: int, extra_attrs: dict[str, object]) -> None:
5293 super().__init__(regular_attr, extra_attrs)
5294 object.__setattr__(self, "sub_attr", sub_attr)
5295
5296 def __setattr__(self, key: str, val: object) -> None:
5297 if key == "sub_attr":
5298 object.__setattr__(self, "sub_attr", val)
5299 elif key == "subclass_var":
5300 raise AttributeError()
5301 else:
5302 super().__setattr__(key, val)
5303
5304 def __delattr__(self, key: str) -> None:
5305 del self._attributes[key]
5306
5307 @mypyc_attr(native_class=False)
5308 class SetAttrNonNative:
5309 _attributes: dict[str, object]
5310 regular_attr: int
5311 class_var: ClassVar[str] = "x"
5312 const: int = 42
5313
5314 def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:
5315 super().__setattr__("_attributes", extra_attrs)
5316 super().__setattr__("regular_attr", regular_attr)
5317
5318 def __setattr__(self, key: str, val: object) -> None:
5319 if key == "regular_attr":
5320 super().__setattr__("regular_attr", val)
5321 elif key == "class_var" or key == "const":
5322 raise AttributeError()
5323 else:
5324 self._attributes[key] = val
5325
5326 def __getattr__(self, key: str) -> object:
5327 return self._attributes.get(key)
5328
5329 class NoSetAttr:
5330 def __init__(self, attr: int) -> None:
5331 self.attr = attr
5332
5333 def object_setattr(self, attr: str, val: object) -> None:
5334 object.__setattr__(self, attr, val)
5335
5336 def super_setattr(self, attr: str, val: object) -> None:
5337 super().__setattr__(attr, val)
5338
5339 @mypyc_attr(native_class=False)
5340 class NoSetAttrNonNative:
5341 def __init__(self, attr: int) -> None:
5342 self.attr = attr
5343
5344 def object_setattr(self, attr: str, val: object) -> None:
5345 object.__setattr__(self, attr, val)
5346
5347 def super_setattr(self, attr: str, val: object) -> None:
5348 super().__setattr__(attr, val)
5349
5350 def __getattr__(self, attr: str) -> object:
5351 pass
5352
5353 [file driver.py]
5354 from native import SetAttr, SetAttrInherited, SetAttrOverridden, SetAttrNonNative, NoSetAttr, NoSetAttrNonNative
5355 from testutil import assertRaises
5356
5357 def test_setattr() -> None:
5358 i = SetAttr(99, {"one": 1})
5359 assert i.class_var == "x"
5360 assert i.regular_attr == 99
5361 assert i.one == 1
5362 assert i.two == None
5363 assert i.const == 42
5364
5365 i.__setattr__("two", "2")
5366 assert i.two == "2"
5367 i.__setattr__("regular_attr", 101)
5368 assert i.regular_attr == 101
5369 with assertRaises(AttributeError):
5370 i.__setattr__("class_var", "y")
5371 with assertRaises(AttributeError):
5372 i.__setattr__("const", 43)
5373
5374 setattr(i, "three", (3,3,3))
5375 assert i.three == (3,3,3)
5376 setattr(i, "regular_attr", 102)
5377 assert i.regular_attr == 102
5378 with assertRaises(AttributeError):
5379 setattr(i, "class_var", "z")
5380 with assertRaises(AttributeError):
5381 setattr(i, "const", 44)
5382
5383 i.four = [4,4]
5384 assert i.four == [4,4]
5385 i.regular_attr = 103
5386 assert i.regular_attr == 103
5387 with assertRaises(AttributeError):
5388 i.const = 45
5389
5390 # Doesn't work because there's no __delattr__.
5391 with assertRaises(AttributeError):
5392 del i.four
5393
5394 def test_setattr_inherited() -> None:
5395 i = SetAttrInherited(99, {"one": 1})
5396 assert i.class_var == "x"
5397 assert i.regular_attr == 99
5398 assert i.one == 1
5399 assert i.two == None
5400 assert i.const == 42
5401
5402 i.__setattr__("two", "2")
5403 assert i.two == "2"
5404 i.__setattr__("regular_attr", 101)
5405 assert i.regular_attr == 101
5406 with assertRaises(AttributeError):
5407 i.__setattr__("class_var", "y")
5408 with assertRaises(AttributeError):
5409 i.__setattr__("const", 43)
5410
5411 setattr(i, "three", (3,3,3))
5412 assert i.three == (3,3,3)
5413 setattr(i, "regular_attr", 102)
5414 assert i.regular_attr == 102
5415 with assertRaises(AttributeError):
5416 setattr(i, "class_var", "z")
5417 with assertRaises(AttributeError):
5418 setattr(i, "const", 44)
5419
5420 i.four = [4,4]
5421 assert i.four == [4,4]
5422 i.regular_attr = 103
5423 assert i.regular_attr == 103
5424 with assertRaises(AttributeError):
5425 i.const = 45
5426
5427 # Doesn't work because there's no __delattr__.
5428 with assertRaises(AttributeError):
5429 del i.four
5430
5431 def test_setattr_overridden() -> None:
5432 i = SetAttrOverridden(99, 1, {"one": 1})
5433 assert i.class_var == "x"
5434 assert i.subclass_var == "y"
5435 assert i.regular_attr == 99
5436 assert i.sub_attr == 1
5437 assert i.one == 1
5438 assert i.two == None
5439 assert i.const == 42
5440
5441 i.__setattr__("two", "2")
5442 assert i.two == "2"
5443 i.__setattr__("regular_attr", 101)
5444 assert i.regular_attr == 101
5445 i.__setattr__("sub_attr", 2)
5446 assert i.sub_attr == 2
5447 with assertRaises(AttributeError):
5448 i.__setattr__("class_var", "y")
5449 with assertRaises(AttributeError):
5450 i.__setattr__("subclass_var", "a")
5451 with assertRaises(AttributeError):
5452 i.__setattr__("const", 43)
5453
5454 setattr(i, "three", (3,3,3))
5455 assert i.three == (3,3,3)
5456 setattr(i, "regular_attr", 102)
5457 assert i.regular_attr == 102
5458 setattr(i, "sub_attr", 3)
5459 assert i.sub_attr == 3
5460 with assertRaises(AttributeError):
5461 setattr(i, "class_var", "z")
5462 with assertRaises(AttributeError):
5463 setattr(i, "subclass_var", "b")
5464 with assertRaises(AttributeError):
5465 setattr(i, "const", 44)
5466
5467 i.four = [4,4]
5468 assert i.four == [4,4]
5469 i.regular_attr = 103
5470 assert i.regular_attr == 103
5471 i.sub_attr = 4
5472 assert i.sub_attr == 4
5473 with assertRaises(AttributeError):
5474 i.const = 45
5475
5476 del i.four
5477 assert "four" not in i._attributes
5478
5479 delattr(i, "three")
5480 assert "three" not in i._attributes
5481
5482 i.__delattr__("two")
5483 assert "two" not in i._attributes
5484
5485 base_ref: SetAttr = i
5486 setattr(base_ref, "sub_attr", 5)
5487 assert base_ref.sub_attr == 5
5488
5489 base_ref.sub_attr = 6
5490 assert base_ref.sub_attr == 6
5491
5492 with assertRaises(AttributeError):
5493 setattr(base_ref, "subclass_var", "c")
5494
5495 base_ref.new_attr = "new_attr"
5496 assert base_ref.new_attr == "new_attr"
5497
5498 del base_ref.new_attr
5499 assert "new_attr" not in base_ref._attributes
5500
5501 def test_setattr_nonnative() -> None:
5502 i = SetAttrNonNative(99, {"one": 1})
5503 assert i.class_var == "x"
5504 assert i.regular_attr == 99
5505 assert i.one == 1
5506 assert i.two == None
5507 assert i.const == 42
5508
5509 i.__setattr__("two", "2")
5510 assert i.two == "2"
5511 i.__setattr__("regular_attr", 101)
5512 assert i.regular_attr == 101
5513 with assertRaises(AttributeError):
5514 i.__setattr__("class_var", "y")
5515 with assertRaises(AttributeError):
5516 i.__setattr__("const", 43)
5517
5518 setattr(i, "three", (3,3,3))
5519 assert i.three == (3,3,3)
5520 setattr(i, "regular_attr", 102)
5521 assert i.regular_attr == 102
5522 with assertRaises(AttributeError):
5523 setattr(i, "class_var", "z")
5524 with assertRaises(AttributeError):
5525 setattr(i, "const", 44)
5526
5527 i.four = [4,4]
5528 assert i.four == [4,4]
5529 i.regular_attr = 103
5530 assert i.regular_attr == 103
5531 with assertRaises(AttributeError):
5532 i.const = 45
5533
5534 # Doesn't work because there's no __delattr__.
5535 with assertRaises(AttributeError):
5536 del i.four
5537
5538 def test_no_setattr() -> None:
5539 i = NoSetAttr(99)
5540 i.super_setattr("attr", 100)
5541 assert i.attr == 100
5542
5543 i.object_setattr("attr", 101)
5544 assert i.attr == 101
5545
5546 object.__setattr__(i, "attr", 102)
5547 assert i.attr == 102
5548
5549 with assertRaises(AttributeError):
5550 i.super_setattr("not_attr", 100)
5551
5552 with assertRaises(AttributeError):
5553 i.object_setattr("not_attr", 101)
5554
5555 with assertRaises(AttributeError):
5556 object.__setattr__(i, "not_attr", 102)
5557
5558 def test_no_setattr_nonnative() -> None:
5559 i = NoSetAttrNonNative(99)
5560 i.super_setattr("attr", 100)
5561 assert i.attr == 100
5562
5563 i.object_setattr("attr", 101)
5564 assert i.attr == 101
5565
5566 object.__setattr__(i, "attr", 102)
5567 assert i.attr == 102
5568
5569 i.super_setattr("one", 100)
5570 assert i.one == 100
5571
5572 i.object_setattr("two", 101)
5573 assert i.two == 101
5574
5575 object.__setattr__(i, "three", 102)
5576 assert i.three == 102
5577
5578 del i.three
5579 assert i.three == None
5580
5581 delattr(i, "two")
5582 assert i.two == None
5583
5584 object.__delattr__(i, "one")
5585 assert i.one == None
5586
5587 test_setattr()
5588 test_setattr_inherited()
5589 test_setattr_overridden()
5590 test_setattr_nonnative()
5591 test_no_setattr()
5592 test_no_setattr_nonnative()
5593
5594 [typing fixtures/typing-full.pyi]
5595
5596 [case testDelAttrWithDeletableAttr]
5597 from testutil import assertRaises
5598
5599 class DelAttr:
5600 __deletable__ = ["del_counter"]
5601
5602 _attributes: dict[str, object]
5603 del_counter: int = 0
5604
5605 def __init__(self) -> None:
5606 object.__setattr__(self, "_attributes", {})
5607
5608 def __setattr__(self, key: str, val: object) -> None:
5609 if key == "del_counter":
5610 object.__setattr__(self, "del_counter", val)
5611 else:
5612 self._attributes[key] = val
5613
5614 def __delattr__(self, key: str) -> None:
5615 if key == "del_counter":
5616 self.del_counter += 1
5617 else:
5618 del self._attributes[key]
5619
5620 def test_deletable_attr() -> None:
5621 i = DelAttr()
5622 assert i.del_counter == 0
5623 del i.del_counter
5624 assert i.del_counter == 1
5625
5626 [case testDelAttrWithDeletableAttrInterpreted]
5627 class DelAttr:
5628 __deletable__ = ["del_counter"]
5629
5630 _attributes: dict[str, object]
5631 del_counter: int = 0
5632
5633 def __init__(self) -> None:
5634 object.__setattr__(self, "_attributes", {})
5635
5636 def __setattr__(self, key: str, val: object) -> None:
5637 if key == "del_counter":
5638 object.__setattr__(self, "del_counter", val)
5639 else:
5640 self._attributes[key] = val
5641
5642 def __delattr__(self, key: str) -> None:
5643 if key == "del_counter":
5644 self.del_counter += 1
5645 else:
5646 del self._attributes[key]
5647
5648 [file driver.py]
5649 from native import DelAttr
5650 from testutil import assertRaises
5651
5652 def test_deletable_attr() -> None:
5653 i = DelAttr()
5654 assert i.del_counter == 0
5655 del i.del_counter
5656 assert i.del_counter == 1
5657
5658 test_deletable_attr()
5659
5660 [case testBufferCorruptedData_librt_internal]
5661 from librt.internal import (
5662 ReadBuffer, read_bool, read_str, read_float, read_int, read_tag, read_bytes
5663 )
5664 from random import randbytes
5665
5666 def check(data: bytes) -> None:
5667 b = ReadBuffer(data)
5668 try:
5669 while True:
5670 read_bool(b)
5671 except ValueError:
5672 pass
5673 b = ReadBuffer(data)
5674 read_tag(b) # Always succeeds
5675 try:
5676 while True:
5677 read_int(b)
5678 except ValueError:
5679 pass
5680 b = ReadBuffer(data)
5681 try:
5682 while True:
5683 read_str(b)
5684 except ValueError:
5685 pass
5686 b = ReadBuffer(data)
5687 try:
5688 while True:
5689 read_bytes(b)
5690 except ValueError:
5691 pass
5692 b = ReadBuffer(data)
5693 try:
5694 while True:
5695 read_float(b)
5696 except ValueError:
5697 pass
5698
5699 import time
5700
5701 def test_read_corrupted_data() -> None:
5702 # Test various deterministic byte sequences (1 to 4 bytes).
5703 t0 = time.time()
5704 for a in range(256):
5705 check(bytes([a]))
5706 for a in range(256):
5707 for b in range(256):
5708 check(bytes([a, b]))
5709 for a in range(32):
5710 for b in range(48):
5711 for c in range(48):
5712 check(bytes([a, b, c]))
5713 for a in range(32):
5714 for b in (0, 5, 17, 34):
5715 for c in (0, 5, 17, 34):
5716 for d in (0, 5, 17, 34):
5717 check(bytes([a, b, c, d]))
5718 # Also test some random data.
5719 for i in range(20000):
5720 data = randbytes(16)
5721 try:
5722 check(data)
5723 except BaseException as e:
5724 print("RANDOMIZED TEST FAILURE -- please open an issue with the following context:")
5725 print(">>>", e, data)
5726 raise
5727
5728 [case testAcyclicClass]
5729 import gc
5730 from mypy_extensions import mypyc_attr
5731
5732 @mypyc_attr(acyclic=True)
5733 class Leaf:
5734 def __init__(self, x: int, s: str) -> None:
5735 self.x = x
5736 self.s = s
5737
5738 def test_basic() -> None:
5739 o = Leaf(5, "hello")
5740 assert o.x == 5
5741 assert o.s == "hello"
5742 o.x = 10
5743 assert o.x == 10
5744
5745 def test_gc_not_tracked() -> None:
5746 o = Leaf(1, "a")
5747 assert not gc.is_tracked(o)
5748
5749 def test_dealloc() -> None:
5750 for i in range(1000):
5751 o = Leaf(i, str(i))
5752 # Just verify no crash or leak during repeated alloc/dealloc
5753
5754 @mypyc_attr(acyclic=True)
5755 class AcyclicBase:
5756 def __init__(self, x: int) -> None:
5757 self.x = x
5758
5759 class DerivedNotAcyclic(AcyclicBase):
5760 """Derived without acyclic -- still participates in GC."""
5761 def __init__(self, x: int, y: str) -> None:
5762 super().__init__(x)
5763 self.y = y
5764
5765 @mypyc_attr(acyclic=True)
5766 class DerivedAcyclic(AcyclicBase):
5767 """Derived with acyclic -- also opts out of GC."""
5768 def __init__(self, x: int, y: str) -> None:
5769 super().__init__(x)
5770 self.y = y
5771
5772 def test_derived_not_acyclic() -> None:
5773 d = DerivedNotAcyclic(3, "hi")
5774 assert d.x == 3
5775 assert d.y == "hi"
5776 # Subclass without @mypyc_attr(acyclic=True) still participates in GC
5777 assert gc.is_tracked(d)
5778
5779 def test_derived_acyclic() -> None:
5780 d = DerivedAcyclic(3, "hi")
5781 assert d.x == 3
5782 assert d.y == "hi"
5783 assert not gc.is_tracked(d)
5784
5785 [case testTraitVtableGrandparentMethod]
5786 from typing import Any
5787 from mypy_extensions import trait
5788
5789 @trait
5790 class Base:
5791 def value(self) -> Any:
5792 return 42
5793
5794 @trait
5795 class Middle(Base):
5796 pass
5797
5798 @trait
5799 class Child(Middle):
5800 def derived(self) -> Any:
5801 return self.value()
5802
5803 class Concrete(Child):
5804 pass
5805
5806 class Sub(Concrete):
5807 def value(self) -> Any:
5808 return 99
5809
5810 [file driver.py]
5811 from native import Concrete, Sub
5812 c = Concrete()
5813 assert c.value() == 42
5814 assert c.derived() == 42
5815 s = Sub()
5816 assert s.value() == 99
5817 assert s.derived() == 99
5818
5819 [case testTraitVtableGrandparentMethodAllowInterpretedSubclasses]
5820 from typing import Any
5821 from mypy_extensions import trait, mypyc_attr
5822
5823 @mypyc_attr(allow_interpreted_subclasses=True)
5824 @trait
5825 class Base:
5826 def value(self) -> Any:
5827 return 42
5828
5829 @mypyc_attr(allow_interpreted_subclasses=True)
5830 @trait
5831 class Middle(Base):
5832 pass
5833
5834 @mypyc_attr(allow_interpreted_subclasses=True)
5835 @trait
5836 class Child(Middle):
5837 def derived(self) -> Any:
5838 return self.value()
5839
5840 @mypyc_attr(allow_interpreted_subclasses=True)
5841 class Concrete(Child):
5842 pass
5843
5844 [file driver.py]
5845 from native import Concrete
5846 c = Concrete()
5847 assert c.value() == 42
5848 assert c.derived() == 42
5849
5850 [case testPropertyShadowVtableGlue]
5851 from typing import List
5852 import mypy_extensions
5853
5854 @mypy_extensions.mypyc_attr(allow_interpreted_subclasses=True)
5855 class Base:
5856 _x: str
5857 _y: List[int]
5858 def __init__(self) -> None:
5859 self._x = ""
5860 self._y = []
5861
5862 @property
5863 def x(self) -> str:
5864 return self._x
5865
5866 @x.setter
5867 def x(self, v: str) -> None:
5868 self._x = v
5869
5870 @property
5871 def y(self) -> List[int]:
5872 return self._y
5873
5874 @y.setter
5875 def y(self, v: List[int]) -> None:
5876 self._y = v
5877
5878 def method(self) -> str:
5879 self.x = "a"
5880 self.y = [1]
5881 return self.x + str(len(self.y))
5882
5883 [file driver.py]
5884 from native import Base
5885
5886 Sub = type("Sub", (Base,), {})
5887 s = Sub()
5888 assert s.method() == "a1"
5889
5890 [case testClassVarSelfReference]
5891 # ClassVar initializers that reference other ClassVars from the same class.
5892 # In CPython, the class body executes as a function where earlier assignments
5893 # are available to later ones. mypyc must replicate this by loading from the
5894 # class being built (type object for ext classes, class dict for non-ext)
5895 # instead of module globals.
5896 from typing import ClassVar, Dict, Set
5897
5898 class Ext:
5899 A: ClassVar[Set[int]] = {1, 2, 3}
5900 B: ClassVar[Set[int]] = {4, 5, 6}
5901 C: ClassVar[Set[int]] = A | B
5902
5903 class ExtChained:
5904 X: ClassVar[Set[int]] = {1, 2}
5905 Y: ClassVar[Set[int]] = X | {3}
5906 Z: ClassVar[Set[int]] = Y | {4}
5907
5908 class ExtDict:
5909 BASE: ClassVar[Dict[str, int]] = {"a": 1, "b": 2}
5910 EXTENDED: ClassVar[Dict[str, int]] = {**BASE, "c": 3}
5911
5912 class ExtSub(Ext):
5913 E: ClassVar[Set[int]] = {7, 8}
5914
5915 [file driver.py]
5916 from native import Ext, ExtChained, ExtDict, ExtSub
5917
5918 assert Ext.A == {1, 2, 3}
5919 assert Ext.B == {4, 5, 6}
5920 assert Ext.C == {1, 2, 3, 4, 5, 6}
5921
5922 assert ExtChained.X == {1, 2}
5923 assert ExtChained.Y == {1, 2, 3}
5924 assert ExtChained.Z == {1, 2, 3, 4}
5925
5926 assert ExtDict.BASE == {"a": 1, "b": 2}
5927 assert ExtDict.EXTENDED == {"a": 1, "b": 2, "c": 3}
5928
5929 assert ExtSub.C == {1, 2, 3, 4, 5, 6}
5930 assert ExtSub.E == {7, 8}
5931
5932 [case testClassVarSelfReferenceNonExt]
5933 # Same as testClassVarSelfReference but for non-extension classes.
5934 from typing import ClassVar, Dict, Set
5935 from mypy_extensions import mypyc_attr
5936
5937 @mypyc_attr(native_class=False)
5938 class NonExt:
5939 A: ClassVar[Set[str]] = {"a", "b"}
5940 B: ClassVar[Set[str]] = {"c"}
5941 C: ClassVar[Set[str]] = A | B
5942
5943 @mypyc_attr(native_class=False)
5944 class NonExtDict:
5945 BASE: ClassVar[Dict[str, int]] = {"x": 1}
5946 EXTENDED: ClassVar[Dict[str, int]] = {**BASE, "y": 2}
5947
5948 @mypyc_attr(native_class=False)
5949 class NonExtChained:
5950 X: ClassVar[Set[int]] = {10}
5951 Y: ClassVar[Set[int]] = X | {20}
5952 Z: ClassVar[Set[int]] = Y | {30}
5953
5954 [file driver.py]
5955 from native import NonExt, NonExtDict, NonExtChained
5956
5957 assert NonExt.A == {"a", "b"}
5958 assert NonExt.B == {"c"}
5959 assert NonExt.C == {"a", "b", "c"}
5960
5961 assert NonExtDict.BASE == {"x": 1}
5962 assert NonExtDict.EXTENDED == {"x": 1, "y": 2}
5963
5964 assert NonExtChained.Z == {10, 20, 30}
5965
5966 [case testPropertyGetterLeak]
5967 class Bar:
5968 pass
5969
5970 class Foo:
5971 def __init__(self) -> None:
5972 self.obj: object = Bar()
5973
5974 @property
5975 def val(self) -> object:
5976 return self.obj
5977
5978 [file other.py]
5979 import gc
5980 from native import Foo, Bar
5981
5982 def check(foo: Foo) -> bool:
5983 return isinstance(foo.val, Bar)
5984
5985 def test_property_getter_no_leak() -> None:
5986 gc.collect()
5987 before = gc.get_objects()
5988 for _ in range(100):
5989 foo = Foo()
5990 check(foo)
5991 gc.collect()
5992 after = gc.get_objects()
5993 diff = len(after) - len(before)
5994 assert diff <= 2, diff
5995
5996 test_property_getter_no_leak()
5997
5998 [file driver.py]
5999 import sys
6000 from other import check
6001 from native import Foo
6002
6003 foo = Foo()
6004 init = sys.getrefcount(foo.obj)
6005 for _ in range(100):
6006 check(foo)
6007 after = sys.getrefcount(foo.obj)
6008 assert after - init == 0, f"Leaked {after - init} refs"