Debian Codegraph @

mypyc/test-data/run-multimodule.test

raw
1 -- These test cases compile two or more modules at a time.
2 -- Any file prefixed with "other" is compiled.
3 --
4 -- Note that these are run in three compilation modes: regular,
5 -- multi-file and separate. See the docstrings of
6 -- mypyc.test.test_run.TestRunMultiFile and
7 -- mypyc.test.test_run.TestRunSeparate for more information.
8 --
9 -- Some of these files perform multiple incremental runs. See
10 -- test-data/unit/check-incremental.test for more information
11 -- about how this is specified (e.g. .2 file name suffixes).
12
13 [case testMultiModulePackage]
14 from p.other import g, _i as i
15 def f(x: int) -> int:
16 from p.other import h
17 return i(h(g(x + 1)))
18 [file p/__init__.py]
19 [file p/other.py]
20 def g(x: int) -> int:
21 return x + 2
22 def h(x: int) -> int:
23 return x + 1
24 def _i(x: int) -> int:
25 return x + 3
26 [file driver.py]
27 import native
28 from native import f
29 from p.other import g
30 assert f(3) == 10
31 assert g(2) == 4
32 try:
33 f(1.1)
34 except TypeError:
35 pass
36 else:
37 assert False
38 try:
39 g(1.1)
40 except TypeError:
41 pass
42 else:
43 assert False
44
45 [case testImportNonNativeSubmoduleFrom]
46 # separate: [(["native.py", "other_pkg/__init__.py"], "testgroup")]
47 import types
48 from other_pkg import helper
49
50 def f() -> int:
51 return helper.func()
52
53 def g() -> types.ModuleType:
54 return helper
55 [file other_pkg/__init__.py]
56 [file other_pkg/helper.py]
57 def func() -> int:
58 return 42
59 [file driver.py]
60 from native import f, g
61 import other_pkg.helper
62 assert f() == 42
63 assert g() is other_pkg.helper
64
65 [case testNativeSubmoduleOfNonNativePackageFrom]
66 # separate: [(["native.py", "pkg/other_mod.py"], "testgroup")]
67 from pkg import other_mod
68
69 def f() -> int:
70 return other_mod.func()
71 [file pkg/__init__.py]
72 [file pkg/other_mod.py]
73 def func() -> int:
74 return 42
75 [file driver.py]
76 import importlib.machinery
77 import os
78 import native
79 import pkg.other_mod
80 assert native.f() == 42
81 # other_mod should be in native's namespace and be the same object as pkg.other_mod
82 assert native.other_mod is pkg.other_mod
83 # native-to-native import should preserve module metadata such as __file__
84 ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES
85 assert any(native.other_mod.__file__.endswith(s) for s in ext_suffixes), native.other_mod.__file__
86 # The directory of __file__ should reflect the package structure relative to the root
87 root_dir = os.path.dirname(native.__file__)
88 assert os.path.dirname(native.other_mod.__file__) == os.path.join(root_dir, "pkg"), \
89 native.other_mod.__file__
90
91 [case testNativeSubmoduleOfNativePackageFrom]
92 # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")]
93 from other_pkg import other_sub
94
95 def f() -> int:
96 return other_sub.func()
97 [file other_pkg/__init__.py]
98 [file other_pkg/other_sub.py]
99 def func() -> int:
100 return 42
101 [file driver.py]
102 import importlib.machinery
103 import os
104 import native
105 import other_pkg.other_sub
106 assert native.f() == 42
107 assert native.other_sub is other_pkg.other_sub
108 # Fast path import should preserve __file__ as a proper extension path
109 ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES
110 assert any(native.other_sub.__file__.endswith(s) for s in ext_suffixes), native.other_sub.__file__
111 # The directory of __file__ should reflect the package structure relative to the root
112 root_dir = os.path.dirname(native.__file__)
113 assert os.path.dirname(native.other_sub.__file__) == os.path.join(root_dir, "other_pkg"), \
114 native.other_sub.__file__
115
116 [case testImportFromBucketingEndToEnd]
117 # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")]
118 from other_pkg import other_sub as sub_alias, other_attr as attr_alias, py_sub as py_alias
119 [file other_pkg/__init__.py]
120 other_attr = 41
121 [file other_pkg/other_sub.py]
122 def func() -> int:
123 return 10
124 [file other_pkg/py_sub.py]
125 def func() -> int:
126 return 20
127 [file driver.py]
128 import importlib
129 import native
130 other_sub = importlib.import_module("other_pkg.other_sub")
131 py_sub = importlib.import_module("other_pkg.py_sub")
132 assert native.sub_alias is other_sub
133 assert native.attr_alias == 41
134 assert native.py_alias is py_sub
135 assert native.sub_alias.func() == 10
136 assert native.py_alias.func() == 20
137
138 [case testNativeTopLevelModuleFileDir]
139 # separate: [(["native.py", "other_top.py"], "testgroup")]
140 import other_top
141
142 def f() -> int:
143 return other_top.func()
144 [file other_top.py]
145 def func() -> int:
146 return 99
147 [file driver.py]
148 import importlib.machinery
149 import os
150 import native
151 import other_top
152 assert native.f() == 99
153 # Top-level native module __file__ directory should match the shared lib's directory
154 ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES
155 assert any(other_top.__file__.endswith(s) for s in ext_suffixes), other_top.__file__
156 root_dir = os.path.dirname(native.__file__)
157 assert os.path.dirname(other_top.__file__) == root_dir, other_top.__file__
158
159 [case testNativeDeeplyNestedSubmoduleFileDir]
160 # separate: [(["native.py", "other_a/__init__.py", "other_a/other_b/__init__.py", "other_a/other_b/other_c.py"], "testgroup")]
161 from other_a.other_b import other_c
162
163 def f() -> int:
164 return other_c.func()
165 [file other_a/__init__.py]
166 [file other_a/other_b/__init__.py]
167 [file other_a/other_b/other_c.py]
168 def func() -> int:
169 return 77
170 [file driver.py]
171 import importlib.machinery
172 import os
173 import native
174 import other_a.other_b.other_c
175 assert native.f() == 77
176 assert native.other_c is other_a.other_b.other_c
177 # Deeply nested module __file__ should have correct extension suffix
178 ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES
179 assert any(native.other_c.__file__.endswith(s) for s in ext_suffixes), native.other_c.__file__
180 # The directory should reflect the full package hierarchy
181 root_dir = os.path.dirname(native.__file__)
182 expected_dir = os.path.join(root_dir, "other_a", "other_b")
183 assert os.path.dirname(native.other_c.__file__) == expected_dir, native.other_c.__file__
184
185 [case testNativeImportPackageAttribute]
186 # separate: [(["native.py", "other_top.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")]
187 import other_top
188 from other_pkg import other_sub
189 import other_pkg
190
191 def get_top() -> str:
192 p = other_top.__package__
193 assert p is not None
194 return p
195
196 def get_sub() -> str:
197 p = other_sub.__package__
198 assert p is not None
199 return p
200
201 def get_pkg() -> str:
202 p = other_pkg.__package__
203 assert p is not None
204 return p
205 [file other_top.py]
206 def func() -> int:
207 return 1
208 [file other_pkg/__init__.py]
209 [file other_pkg/other_sub.py]
210 def func() -> int:
211 return 2
212 [file driver.py]
213 from native import get_top, get_sub, get_pkg
214
215 # Top-level module: __package__ should be "" (empty string)
216 assert get_top() == "", repr(get_top())
217
218 # Submodule: __package__ should be the parent package name
219 assert get_sub() == "other_pkg", repr(get_sub())
220
221 # Package __init__: __package__ should be the package name itself
222 assert get_pkg() == "other_pkg", repr(get_pkg())
223
224 [case testNativeImportFileAvailableAtInitTime]
225 # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")]
226 from other_pkg import other_sub
227
228 def f() -> int:
229 return other_sub.func()
230 [file other_pkg/__init__.py]
231 [file other_pkg/other_sub.py]
232 # __file__ should be available during module initialization
233 _file: str = __file__
234
235 def func() -> int:
236 return 42
237 [file driver.py]
238 import importlib.machinery
239 import native
240 assert native.f() == 42
241 # Verify that __file__ captured at init time has a valid extension suffix
242 ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES
243 assert any(native.other_sub._file.endswith(s) for s in ext_suffixes), native.other_sub._file
244
245 [case testNativeImportPathAttribute]
246 # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")]
247 import other_pkg
248 from other_pkg import other_sub
249
250 def get_pkg_path() -> str:
251 return other_pkg.__path__[0]
252
253 def get_sub_has_path() -> bool:
254 return hasattr(other_sub, '__path__')
255 [file other_pkg/__init__.py]
256 # __path__ should be available during package initialization
257 _path: list[str] = __path__
258 [file other_pkg/other_sub.py]
259 def func() -> int:
260 return 1
261 [file driver.py]
262 import os
263 import native
264
265 # Package should have __path__ set to [dirname(__file__)]
266 expected = os.path.dirname(native.other_pkg.__file__)
267 assert native.get_pkg_path() == expected, (native.get_pkg_path(), expected)
268
269 # __path__ should have been accessible at init time
270 assert native.other_pkg._path == [expected], native.other_pkg._path
271
272 # Non-package submodule should NOT have __path__
273 assert not native.get_sub_has_path()
274
275 [case testNativeImportPackageFileDirMatchesPath]
276 # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")]
277 import other_pkg
278 from other_pkg import other_sub
279
280 def get_pkg_file() -> str:
281 return other_pkg.__file__
282
283 def get_pkg_path() -> str:
284 return other_pkg.__path__[0]
285
286 def get_sub_file() -> str:
287 return other_sub.__file__
288 [file other_pkg/__init__.py]
289 x = 1
290 [file other_pkg/other_sub.py]
291 def func() -> int:
292 return 1
293 [file driver.py]
294 import os
295 import native
296
297 pkg_file = native.get_pkg_file()
298 pkg_path = native.get_pkg_path()
299 sub_file = native.get_sub_file()
300
301 # Package __file__ should contain __init__ (e.g. other_pkg/__init__.cpython-312-x86_64-linux-gnu.so)
302 assert "__init__" in os.path.basename(pkg_file), \
303 f"Package __file__ should contain __init__, got: {pkg_file}"
304
305 # Package __path__ should be the directory containing the package's __init__ file
306 assert pkg_path == os.path.dirname(pkg_file), \
307 f"__path__ ({pkg_path}) should equal dirname(__file__) ({os.path.dirname(pkg_file)})"
308
309 # __path__ should end with the package name
310 assert os.path.basename(pkg_path) == "other_pkg", \
311 f"__path__ should end with package name, got: {pkg_path}"
312
313 # Submodule __file__ should be inside the package directory (i.e. inside __path__)
314 assert os.path.dirname(sub_file) == pkg_path, \
315 f"Submodule dir ({os.path.dirname(sub_file)}) should equal package __path__ ({pkg_path})"
316
317 [case testNativeImportSpecAttribute]
318 # separate: [(["native.py", "other_top.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")]
319 from typing import Any
320 import other_top
321 from other_pkg import other_sub
322 import other_pkg
323
324 def get_top_spec() -> Any:
325 return other_top.__spec__
326
327 def get_sub_spec() -> Any:
328 return other_sub.__spec__
329
330 def get_pkg_spec() -> Any:
331 return other_pkg.__spec__
332 [file other_top.py]
333 from typing import Any
334 # __spec__ should be available during module initialization
335 _spec: Any = __spec__ # type: ignore[name-defined]
336
337 def func() -> int:
338 return 1
339 [file other_pkg/__init__.py]
340 [file other_pkg/other_sub.py]
341 def func() -> int:
342 return 2
343 [file driver.py]
344 import importlib.machinery
345 import native
346
347 top_spec = native.get_top_spec()
348 sub_spec = native.get_sub_spec()
349 pkg_spec = native.get_pkg_spec()
350
351 # __spec__.name should match the module name
352 assert top_spec.name == "other_top"
353 assert sub_spec.name == "other_pkg.other_sub"
354 assert pkg_spec.name == "other_pkg"
355
356 # __spec__ should have correct origin (same as __file__)
357 assert top_spec.origin == native.other_top.__file__
358 assert sub_spec.origin == native.other_sub.__file__
359
360 # __spec__.loader should be an ExtensionFileLoader and also be set as __loader__
361 assert isinstance(top_spec.loader, importlib.machinery.ExtensionFileLoader)
362 assert native.other_top.__loader__ is top_spec.loader
363
364 # Package spec should have submodule_search_locations
365 assert pkg_spec.submodule_search_locations is not None
366
367 # Non-package spec should not have submodule_search_locations
368 assert top_spec.submodule_search_locations is None
369
370 # __spec__ should be available at init time
371 assert native.other_top._spec.name == "other_top"
372
373 [case testNativeSubmoduleFailureDoesNotBindParentEarly]
374 # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")]
375 from other_pkg import other_sub
376 [file other_pkg/__init__.py]
377 x = 1
378 [file other_pkg/other_sub.py]
379 import other_pkg
380
381 if hasattr(other_pkg, "other_sub"):
382 raise RuntimeError("parent attr visible too early")
383 raise RuntimeError("boom from other_sub")
384 [file driver.py]
385 import sys
386 import other_pkg
387
388 try:
389 import native
390 except RuntimeError as e:
391 assert str(e) == "boom from other_sub"
392 else:
393 assert False, "import native should fail"
394
395 assert not hasattr(other_pkg, "other_sub")
396 assert "other_pkg.other_sub" not in sys.modules
397
398 [case testNativeImportUsesExistingNativeSysModulesObject]
399 # separate: [(["native.py", "other_top.py"], "testgroup")]
400 import other_top
401
402 def f() -> int:
403 return other_top.value
404 [file other_top.py]
405 value = 42
406 [file driver.py]
407 import native
408 import other_top
409
410 assert native.other_top is other_top
411 assert native.f() == 42
412
413 [case testNativeImportRejectsForeignSysModulesObject]
414 # separate: [(["native.py", "other_top.py"], "testgroup")]
415 import other_top
416
417 def f() -> int:
418 return other_top.value
419 [file other_top.py]
420 value = 42
421 [file driver.py]
422 import sys
423 import types
424
425 import other_top
426
427 fake = types.ModuleType("other_top")
428 fake.value = -1
429 sys.modules["other_top"] = fake
430
431 try:
432 import native
433 except ImportError as e:
434 assert "other_top" in str(e)
435 assert "replaced after initialization" in str(e)
436 else:
437 assert False, "import native should fail"
438
439 assert sys.modules["other_top"] is fake
440
441 [case testMultiModuleFastpaths]
442 [file other_main.py]
443
444 [file other_main.py.2]
445 from other_b import A, func
446
447 class B(A):
448 pass
449
450 def test() -> None:
451 a = A()
452 assert func() == 12
453 assert a.method() == "test"
454
455 test()
456
457 [file other_b.py]
458 class A:
459 def method(self) -> str:
460 return "test"
461
462 def func() -> int:
463 return 12
464
465 # Remove all the methods and functions from globals to ensure that
466 # they get called via the fastpaths even when doing incremental
467 # compilation.
468 setattr(A, 'method', None)
469 setattr(A, '__init__', None)
470 globals()['func'] = None
471 globals()['A'] = None
472
473 [file driver.py]
474 import other_main
475
476 [case testNonNativeImportInPackageFile]
477 # The import is really non-native only in separate compilation mode where __init__.py and
478 # other_cache.py are in different libraries and the import uses the standard Python procedure.
479 # Python imports are resolved using __path__ and __spec__ from the package file so this checks
480 # that they are set up correctly.
481 [file other/__init__.py]
482 from other.other_cache import Cache
483
484 x = 1
485 [file other/other_cache.py]
486 class Cache:
487 pass
488
489 [file driver.py]
490 import other
491
492 [case testRelativeImportInPackageFile]
493 # Relative imports from a compiled package __init__ depend on package metadata being
494 # available while the package module body is executing.
495 [file other/__init__.py]
496 assert __package__ == "other"
497 from .other_cache import Cache
498
499 x = 1
500 [file other/other_cache.py]
501 class Cache:
502 pass
503
504 [file driver.py]
505 import other
506 assert other.Cache.__name__ == "Cache"
507
508 [case testMultiModuleSameNames]
509 # Use same names in both modules
510 import other
511 def f() -> int:
512 return 0
513 class C:
514 x: int
515 def __init__(self) -> None:
516 self.x = 1
517 def f(self, x: int) -> int:
518 return self.x + x
519 class D(C): pass
520
521 def g(x: 'other.C') -> None:
522 pass
523
524 [file other.py]
525 def f(x: int) -> int:
526 return x + 1
527 class C:
528 x: int
529 def __init__(self) -> None:
530 self.x = 2
531 def f(self, x: int) -> int:
532 return self.x + x + 1
533 class D(C): pass
534 [file driver.py]
535 import native, other
536 assert native.f() == 0
537 assert other.f(3) == 4
538 c1 = native.C()
539 c1.x += 3
540 c2 = other.C()
541 c2.x += 6
542 assert c1.f(9) == 1 + 3 + 9
543 assert c2.f(7) == 2 + 6 + 7 + 1
544 assert isinstance(native.D(), native.C)
545 assert isinstance(other.D(), other.C)
546 assert not isinstance(native.D(), other.C)
547 assert not isinstance(other.D(), native.C)
548
549 [case testMultiModuleInitializeImportedModules]
550 from other import f
551
552 def g() -> int:
553 return f(1)
554 [file other.py]
555 def f(x: int) -> int:
556 return x + 4
557 [file driver.py]
558 import sys
559 assert 'other' not in sys.modules
560 from native import g
561 assert 'other' in sys.modules
562 assert g() == 5
563 f = sys.modules['other'].f
564 assert f(1) == 5
565 try:
566 f(1.1)
567 except TypeError:
568 pass
569 else:
570 assert False
571
572 [case testMultiModuleImportClass]
573 from typing import cast
574 from other import C, a_global
575
576 class D(C):
577 def __init__(self, x: int) -> None:
578 self.x = x
579
580 def f(c: C) -> int:
581 d = D(3)
582 o: object = c
583 c = cast(C, o)
584 return a_global + c.x + c.f() + d.x + d.f() + 1
585 [file other.py]
586 from typing import Final
587 a_global: Final = int('5')
588
589 class C:
590 x: int
591
592 def __init__(self, x: int) -> None:
593 self.x = x
594
595 def __hash__(self) -> int:
596 return self.x
597
598 def __str__(self) -> str:
599 return str(self.x)
600
601 def f(self) -> int:
602 return 2
603
604 def check(self) -> None:
605 assert isinstance(self, C)
606
607 [file driver.py]
608 from native import f, D
609 from other import C
610 c = C(4)
611 assert f(c) == 5 + 4 + 2 + 3 + 2 + 1
612 assert str(D(10)) == '10'
613 assert hash(10) == 10
614 try:
615 f(1)
616 except TypeError:
617 pass
618 else:
619 assert False
620
621 assert isinstance(D(10), C)
622
623 c.check()
624 D(10).check()
625
626 [case testMultiModuleSpecialize]
627 from other import A
628
629 class B(A):
630 def foo(self, x: object) -> int:
631 print(2)
632 return id(x)
633 [file other.py]
634 class A:
635 def foo(self, x: int) -> object:
636 print(1)
637 return str(x)
638
639 def use_a(x: A, y: int) -> object:
640 return x.foo(y)
641
642 [file driver.py]
643 from native import B
644 from other import A, use_a
645 a = A()
646 b = B()
647 o = object()
648 i = 10
649 assert a.foo(10) == '10'
650 assert b.foo(o) == id(o)
651 assert use_a(a, 10) == '10'
652 assert use_a(b, i) == id(i)
653 [out]
654 1
655 2
656 1
657 2
658
659 [case testMultiModuleLiterals]
660 from other import gs, gi, gf
661
662 def fs() -> str:
663 return 'f' + gs()
664 def fi() -> int:
665 return 10001000100010001000 + gi()
666 def ff() -> float:
667 return 2.0 + gf()
668 [file other.py]
669 def gi() -> int:
670 return 20001000100010001000
671 def gs() -> str:
672 return 'g'
673 def gf() -> float:
674 return 3.0
675 [file driver.py]
676 from native import fs, fi, ff
677 assert fs() == 'fg'
678 assert fi() == 30002000200020002000
679 assert ff() == 5.0
680
681 [case testMultiModuleTraceback]
682 from other import fail2
683
684 def fail() -> None:
685 fail2()
686 [file other.py]
687 def fail2() -> None:
688 x = [1]
689 x[2] = 2
690 [file driver.py]
691 import traceback
692 import sys
693 import native
694 import other
695 try:
696 other.fail2()
697 except IndexError:
698 tb = sys.exc_info()[2]
699 assert tb.tb_next.tb_frame.f_globals is other.__dict__
700 traceback.print_exc()
701 try:
702 native.fail()
703 except IndexError:
704 tb = sys.exc_info()[2]
705 assert tb.tb_next.tb_frame.f_globals is native.__dict__
706 traceback.print_exc()
707 [out]
708 Traceback (most recent call last):
709 File "driver.py", line 6, in <module>
710 other.fail2()
711 File "other.py", line 3, in fail2
712 x[2] = 2
713 IndexError: list assignment index out of range
714 Traceback (most recent call last):
715 File "driver.py", line 12, in <module>
716 native.fail()
717 File "native.py", line 4, in fail
718 fail2()
719 File "other.py", line 3, in fail2
720 x[2] = 2
721 IndexError: list assignment index out of range
722 [out version>=3.13]
723 Traceback (most recent call last):
724 File "driver.py", line 6, in <module>
725 other.fail2()
726 ~~~~~~~~~~~^^
727 File "other.py", line 3, in fail2
728 x[2] = 2
729 IndexError: list assignment index out of range
730 Traceback (most recent call last):
731 File "driver.py", line 12, in <module>
732 native.fail()
733 ~~~~~~~~~~~^^
734 File "native.py", line 4, in fail
735 fail2()
736 File "other.py", line 3, in fail2
737 x[2] = 2
738 IndexError: list assignment index out of range
739
740 [case testMultiModuleCycle]
741 if False:
742 from typing import Final
743 import other
744
745 x = int('0') # type: Final
746
747 def f1() -> int:
748 return other.f2() + other.x
749
750 def f3() -> int:
751 return 5
752 [file other.py]
753 if False:
754 from typing import Final
755 import native
756
757 x = int('0') # type: Final
758
759 def f2() -> int:
760 return native.f3() + native.x
761 [file driver.py]
762 from native import f1
763 assert f1() == 5
764
765 [case testMultiModuleCycleWithClasses]
766 import other
767
768 class D: pass
769
770 def f() -> other.C:
771 return other.C()
772
773 def g(c: other.C) -> D:
774 return c.d
775
776 [file other.py]
777 import native
778
779 class C:
780 def __init__(self) -> None:
781 self.d = native.D()
782
783 def h(d: native.D) -> None:
784 pass
785
786 [file driver.py]
787 from native import f, g
788 from other import C, h
789
790 c = f()
791 assert isinstance(c, C)
792 assert g(c) is c.d
793 h(c.d)
794
795 try:
796 g(1)
797 except TypeError:
798 pass
799 else:
800 assert False
801
802 try:
803 h(1)
804 except TypeError:
805 pass
806 else:
807 assert False
808
809 [case testMultiModuleCycleWithInheritance]
810 import other
811
812 class Deriv1(other.Base1):
813 def __init__(self) -> None:
814 super().__init__()
815
816 class Base2:
817 y: int
818 def __init__(self) -> None:
819 self.y = 2
820
821 [file other.py]
822 from typing import Tuple
823 import native
824
825 class Base1:
826 a: Tuple[int, int]
827 x: int
828 def __init__(self) -> None:
829 self.x = 1
830
831 def make_2() -> native.Base2:
832 return native.Base2()
833
834 [file driver.py]
835 from native import Deriv1
836 from other import make_2
837 a = Deriv1()
838 assert a.x == 1
839 b = make_2()
840 assert b.y == 2
841
842 [case testMultiModuleTraitInheritance]
843 from other import Base1, Base2
844
845 class Deriv1(Base1, Base2):
846 pass
847
848 [file other.py]
849 from mypy_extensions import trait
850
851 @trait
852 class Base1:
853 def foo(self) -> int: return 10
854 @trait
855 class Base2:
856 def bar(self) -> int: return 12
857
858 [file driver.py]
859 from native import Deriv1
860 a = Deriv1()
861 assert a.foo() == 10 and a.bar() == 12
862
863
864 [case testImportCycleWithNonCompiledModule]
865 import m
866
867 class C: pass
868
869 def f1() -> int:
870 m.D()
871 return m.f2()
872
873 def f3() -> int:
874 return 2
875
876 [file m.py]
877 # This module is NOT compiled
878 import native
879
880 class D: pass
881
882 def f2() -> int:
883 native.C()
884 return native.f3()
885
886 [file driver.py]
887 from native import f1
888
889 assert f1() == 2
890
891 [case testImportCycleWithTopLevelStatements]
892 import other
893 x = 1
894 print(x)
895
896 [file other.py]
897 import native
898 x = 2
899 print(x)
900
901 [file driver.py]
902 import other
903 print('-')
904 import native
905 print('>', native.x)
906 print('>', other.x)
907
908 [out]
909 1
910 2
911 -
912 > 1
913 > 2
914
915 [case testMultiModuleCycleIfMypy1]
916 from other import foo, bar
917
918 class Foo:
919 def foo(self) -> None:
920 foo(self)
921 class Bar:
922 def bar(self) -> None:
923 bar(self)
924
925 [file other.py]
926 from typing import TYPE_CHECKING
927 MYPY = False
928 if MYPY:
929 from native import Foo
930 if TYPE_CHECKING:
931 from native import Bar
932
933 def foo(x: 'Foo') -> None:
934 pass
935 def bar(x: 'Bar') -> None:
936 pass
937
938 [file driver.py]
939 from native import Foo, Bar
940 Foo().foo()
941 Bar().bar()
942
943 [case testMultiModuleCycleIfMypy2]
944 MYPY = False
945 if MYPY:
946 from other import C
947
948 class D:
949 def __init__(self) -> None:
950 self.y = 1
951
952 def f(c: 'C') -> int:
953 return c.x
954
955 [file other.py]
956 from typing import TYPE_CHECKING
957 if TYPE_CHECKING:
958 from native import D
959
960 class C:
961 def __init__(self) -> None:
962 self.x = 2
963
964 def g(d: 'D') -> int:
965 return d.y
966
967 [file driver.py]
968 from native import f, D
969 from other import g, C
970
971 assert f(C()) == 2
972 assert g(D()) == 1
973
974 try:
975 f(D())
976 except TypeError:
977 pass
978 else:
979 assert False
980
981 try:
982 g(C())
983 except TypeError:
984 pass
985 else:
986 assert False
987
988 [case testMultiModuleRelative]
989 from package.a import f
990 [file package/__init__.py]
991 [file package/a.py]
992 from . import b
993 from .c import c3
994 def f() -> None:
995 print("Hello " + b.b2())
996 print("Hello " + c3())
997 [file package/b.py]
998 def b2() -> str:
999 return "moon!"
1000 [file package/c.py]
1001 def c3() -> str:
1002 return "sun!"
1003
1004 [file driver.py]
1005 from native import f
1006 f()
1007 [out]
1008 Hello moon!
1009 Hello sun!
1010
1011 [case testMultiModuleCrash]
1012 b = False
1013 if b:
1014 import other
1015
1016 def foo() -> None:
1017 try:
1018 other.x
1019 except:
1020 pass
1021 else:
1022 assert False
1023
1024 [file other.py]
1025 x = 10
1026
1027 [file driver.py]
1028 from native import foo
1029 foo()
1030
1031 [case testTrivialIncremental]
1032 # separate: [(["other.py", "other_b.py"], "stuff")]
1033 from other import x
1034 from other_b import z
1035 y = x + z
1036 [file other.py]
1037 x = 1
1038 [file other.py.2]
1039 x = 2
1040 [file other_b.py]
1041 z = 1
1042
1043 [file driver.py]
1044 from native import y
1045 print(y)
1046 [out]
1047 2
1048 [out2]
1049 3
1050 [rechecked other, other_b]
1051
1052 [case testIncrementalCompilation1]
1053 import non_native
1054 from other_a import A
1055 from other_b import z
1056
1057 a = A()
1058 assert a.y == z
1059
1060 assert non_native.foo() == 0
1061
1062 [file other_a.py]
1063 from other_b import z
1064 from typing import Iterable
1065
1066 class A:
1067 def __init__(self) -> None:
1068 self.y = z
1069 [file other_a.py.2]
1070 from other_b import z
1071 from typing import Iterable
1072
1073 class A:
1074 def __init__(self) -> None:
1075 self.x = 'test'
1076 self.y = z
1077 [file other_b.py]
1078 import other_a
1079
1080 z = 10
1081
1082 def foo() -> 'other_a.A':
1083 return other_a.A()
1084 [file other_b.py.3]
1085 import other_a
1086
1087 z = 20
1088
1089 def foo() -> 'other_a.A':
1090 return other_a.A()
1091
1092 [file non_native.py]
1093 import other_a
1094
1095 def foo() -> int:
1096 return 0
1097
1098 [file non_native.py.4]
1099 import other_a
1100
1101 def foo() -> float:
1102 return 0
1103
1104 [file driver.py]
1105 from native import a
1106 print(a.y, getattr(a, 'x', None))
1107
1108 [out]
1109 10 None
1110 [out2]
1111 10 test
1112 [out3]
1113 20 test
1114 [out4]
1115 20 test
1116
1117 [rechecked other_a, other_b, native, non_native]
1118 [rechecked2 other_a, other_b]
1119 [rechecked3 native, non_native]
1120
1121
1122 -- This one tests a group that is not an SCC.
1123 [case testIncrementalCompilation2]
1124 # separate: [(["other_a.py", "other_b.py"], "stuff")]
1125 from other_a import A
1126 from other_b import z
1127
1128 a = A()
1129 assert a.y == z
1130
1131 [file other_a.py]
1132 from other_b import z
1133
1134 class A:
1135 def __init__(self) -> None:
1136 self.y = z
1137 [file other_a.py.2]
1138 from other_b import z
1139
1140 class A:
1141 def __init__(self) -> None:
1142 self.x = 'test'
1143 self.y = z
1144
1145 [file other_b.py]
1146 z = 10
1147
1148 [file driver.py]
1149 from native import a
1150 print(a.y, getattr(a, 'x', None))
1151
1152 [out]
1153 10 None
1154 [out2]
1155 10 test
1156
1157 [rechecked other_a, other_b, native]
1158
1159 [case testIncrementalCompilation3]
1160 from other import X
1161 Y = X
1162 def foo() -> int:
1163 return X
1164
1165 [file other.py]
1166 from typing import Final
1167 X: Final = 10
1168
1169 [file other.py.2]
1170 from typing import Final
1171 X: Final = 20
1172
1173 [file driver.py]
1174 import native
1175 import other
1176 assert native.Y == other.X
1177 assert native.foo() == other.X
1178
1179 [rechecked native, other]
1180
1181 -- This one tests a group changing
1182 [case testIncrementalCompilation4]
1183 # separate: [(["other_a.py", "other_b.py"], "stuff")]
1184 # separate2: []
1185 from other_a import A
1186 from other_b import z
1187
1188 a = A()
1189 assert a.y == z
1190
1191 [file other_a.py]
1192 from other_b import z
1193
1194 class A:
1195 def __init__(self) -> None:
1196 self.y = z
1197
1198 [file other_b.py]
1199 z = 10
1200
1201 [file wtvr.py.2]
1202
1203 [file driver.py]
1204 from native import a
1205 print(a.y, getattr(a, 'x', None))
1206
1207 [out]
1208 10 None
1209 [out2]
1210 10 None
1211
1212 [rechecked other_a, other_b, native]
1213
1214 -- This one tests cases where other modules *do not* need rechecked
1215 [case testIncrementalCompilation5]
1216 import other_a
1217 [file other_a.py]
1218 from other_b import f
1219 assert f(10) == 20
1220 [file other_a.py.2]
1221 from other_b import f
1222 assert f(20) == 40
1223
1224 [file other_b.py]
1225 def f(x: int) -> int:
1226 return x * 2
1227
1228 [file driver.py]
1229 import native
1230
1231 [rechecked other_a]
1232
1233 -- Delete one of the C files and make sure this forces recompilation
1234 [case testIncrementalCompilation6]
1235 import other_a
1236 assert other_a.foo() == 10
1237 [file other_a.py]
1238 def foo() -> int: return 10
1239
1240 [file build/__native_other_a.c]
1241
1242 [delete build/__native_other_a.c.2]
1243
1244 [file driver.py]
1245 import native
1246
1247 [rechecked other_a]
1248
1249 -- Test that importing a skipped module does not force rechecks.
1250 [case testIncrementalCompilationFollowImportsSkip]
1251 from other_dep import f
1252 assert f() == 1
1253
1254 [file other_dep.py]
1255 import skipped
1256
1257 def f() -> int:
1258 return 1
1259
1260 def g() -> int:
1261 return 2
1262
1263 # Files under "skipped" are not typechecked because of the "--follow_imports = skip" option.
1264 [file skipped/__init__.py]
1265 x = 1
1266
1267 [file skipped/other_child.py]
1268 import skipped
1269
1270 def child() -> int:
1271 return 1
1272
1273 [file native.py.2]
1274 from other_dep import g
1275 assert g() == 2
1276
1277 [file driver.py]
1278 import native
1279
1280 [rechecked native]
1281
1282 [case testSeparateCompilationWithUndefinedAttribute]
1283 from other_a import A
1284
1285 def f() -> None:
1286 a = A()
1287 if a.x == 5:
1288 print(a.y)
1289 print(a.m())
1290 else:
1291 assert a.x == 6
1292 try:
1293 print(a.y)
1294 except AttributeError:
1295 print('y undefined')
1296 else:
1297 assert False
1298
1299 try:
1300 print(a.m())
1301 except AttributeError:
1302 print('y undefined')
1303 else:
1304 assert False
1305
1306 [file other_a.py]
1307 from other_b import B
1308
1309 class A(B):
1310 def __init__(self) -> None:
1311 self.y = 9
1312
1313 [file other_a.py.2]
1314 from other_b import B
1315
1316 class A(B):
1317 x = 6
1318
1319 def __init__(self) -> None:
1320 pass
1321
1322 [file other_b.py]
1323 class B:
1324 x = 5
1325
1326 def __init__(self) -> None:
1327 self.y = 7
1328
1329 def m(self) -> int:
1330 return self.y
1331
1332 [file driver.py]
1333 from native import f
1334 f()
1335
1336 [rechecked native, other_a]
1337
1338 [out]
1339 9
1340 9
1341 [out2]
1342 y undefined
1343 y undefined
1344
1345 [case testIncrementalCompilationWithDeletable]
1346 import other_a
1347 [file other_a.py]
1348 from other_b import C
1349 [file other_a.py.2]
1350 from other_b import C
1351 c = C()
1352 print(getattr(c, 'x', None))
1353 del c.x
1354 print(getattr(c, 'x', None))
1355 [file other_b.py]
1356 class C:
1357 __deletable__ = ['x']
1358 def __init__(self) -> None:
1359 self.x = 0
1360 [file driver.py]
1361 import native
1362 [out]
1363 [out2]
1364 0
1365 None
1366
1367 [case testIncrementalCompilationWithNonClassTypeDef]
1368 import other_a
1369 [file other_a.py]
1370 from other_b import MyInt
1371 [file other_a.py.2]
1372 from other_b import MyInt, NT, TD
1373 i = MyInt(42)
1374
1375 def f(x: MyInt) -> int:
1376 return x + 1
1377
1378 def g(x: int) -> MyInt:
1379 return MyInt(x + 2)
1380
1381 print(i)
1382 print(f(i))
1383 print(g(13))
1384
1385 def make_nt(x: int) -> NT:
1386 return NT(x=MyInt(x))
1387
1388 print(make_nt(4))
1389
1390 def make_td(x: int) -> TD:
1391 return {"x": MyInt(x)}
1392
1393 print(make_td(5))
1394
1395 [file other_b.py]
1396 from typing import NewType, NamedTuple, TypedDict
1397 from enum import Enum
1398
1399 MyInt = NewType("MyInt", int)
1400 NT = NamedTuple("NT", [("x", MyInt)])
1401 TD = TypedDict("TD", {"x": MyInt})
1402
1403 [file driver.py]
1404 import native
1405
1406 [typing fixtures/typing-full.pyi]
1407 [out]
1408 [out2]
1409 42
1410 43
1411 15
1412 NT(x=4)
1413 {'x': 5}
1414
1415 [case testExtraLibRtSourceFileDep]
1416 table_list = list(range(256))
1417 table_list[ord('A')] = ord('B')
1418 table = bytes(table_list)
1419
1420 def translate(b: bytes) -> bytes:
1421 # The primimitive for bytes.translate requires an optional C file from lib-rt
1422 return b.translate(table)
1423 [file driver.py]
1424 import native
1425 assert native.translate(b'ABCD') == b'BBCD'
1426
1427 [case testIncrementalCrossGroupExportTableOffsets]
1428 # Regression: under separate=True, each consumer module's IR is
1429 # compiled against the positional layout of its deps'
1430 # `exports_<group>` struct. Reordering the dep's classes keeps the
1431 # same set of public names, so mypy's interface hash for the dep is
1432 # unchanged -- the consumer is not invalidated and stays fully
1433 # cached, which causes `_load_cached_group_files` to return empty
1434 # cfile content for the consumer's group.
1435 #
1436 # Before the fix, `get_header_deps` over empty content returned no
1437 # includes, so `Extension.depends` for the consumer ended up empty
1438 # and setuptools never recompiled the consumer's .o when the dep's
1439 # `__native_<dep>.h` shifted struct offsets. The stale .o kept the
1440 # old offsets and silently resolved cross-group calls to the wrong
1441 # class.
1442 from other_classes import Gamma, Delta
1443
1444 def make_gamma() -> Gamma:
1445 return Gamma()
1446
1447 def make_delta() -> Delta:
1448 return Delta()
1449
1450 [file other_classes.py]
1451 class Alpha:
1452 a: int = 1
1453
1454 class Beta:
1455 b: int = 2
1456
1457 class Gamma:
1458 g: int = 3
1459
1460 class Delta:
1461 d: int = 4
1462
1463 [file other_classes.py.2]
1464 class Delta:
1465 d: int = 4
1466
1467 class Alpha:
1468 a: int = 1
1469
1470 class Beta:
1471 b: int = 2
1472
1473 class Gamma:
1474 g: int = 3
1475
1476 [file driver.py]
1477 import native
1478 assert type(native.make_gamma()).__name__ == "Gamma"
1479 assert type(native.make_delta()).__name__ == "Delta"
1480
1481 [case testCrossModuleAttrDefaults]
1482 from other import Parent
1483
1484 class Child(Parent):
1485 extra: int = 99
1486
1487 def test() -> None:
1488 c = Child()
1489 assert c.config == {"key": "value"}
1490 assert c.extra == 99
1491 assert c.total == 60
1492 p = Parent()
1493 assert p.config == {"key": "value"}
1494 assert p.total == 60
1495 assert Parent.TAG == "parent"
1496
1497 [file other.py]
1498 from typing import ClassVar, Dict
1499 MY_DEFAULT: Dict[str, str] = {"key": "value"}
1500 VAL_1: int = 10
1501 VAL_2: int = 20
1502 VAL_3: int = 30
1503
1504 class Parent:
1505 config: Dict[str, str] = MY_DEFAULT
1506 total: int = VAL_1 + VAL_2 + VAL_3
1507 TAG: ClassVar[str] = "parent"
1508
1509 [file driver.py]
1510 from native import test
1511 test()
1512
1513 [case testIncrementalCrossModuleInheritedAttrDefaults]
1514 # Regression: under separate=True, when only the subclass module is
1515 # recompiled (parent loaded from mypy's incremental cache, so its
1516 # ClassDef.defs.body is empty), the subclass produces no
1517 # __mypyc_defaults_setup of its own and ClassIR.get_method returns
1518 # the parent's. The emitted call must use the cross-group
1519 # exports_<group>. prefix, otherwise the generated C references an
1520 # undeclared symbol and clang/gcc fail to compile.
1521 import other_a
1522
1523 def test() -> None:
1524 c = other_a.Child()
1525 assert c.x == 1
1526 assert c.y == "hello"
1527
1528 [file other_b.py]
1529 class Parent:
1530 x: int = 1
1531 y: str = "hello"
1532
1533 [file other_a.py]
1534 from other_b import Parent
1535
1536 class Child(Parent):
1537 pass
1538
1539 [file other_a.py.2]
1540 from other_b import Parent
1541
1542 class Child(Parent):
1543 pass
1544
1545 def _force_recompile() -> int:
1546 return 1
1547
1548 [file driver.py]
1549 from native import test
1550 test()
1551
1552 [case testExtraOpsFunction_experimental_librt]
1553 from librt.strings import BytesWriter
1554
1555 def call_write(b: bytes) -> bytes:
1556 w = BytesWriter()
1557 w.write(b) # calls CPyBytesWriter_Write defined in byteswriter_extra_ops.c
1558 return w.getvalue()
1559
1560 [file other.py]
1561 from native import call_write
1562
1563 def test(b: bytes) -> bytes:
1564 return call_write(b)
1565
1566 [file driver.py]
1567 from other import test
1568
1569 input = b'x' * 512
1570 assert test(input) == input
1571
1572 [case testLibrtDependencyInImportedFile_experimental_librt]
1573 # Test that a compiled file (other.py) that does not depend on librt can import another compiled
1574 # file (native.py) that does.
1575 from librt.vecs import vec, append, pop
1576
1577 def call_append(s: str) -> str:
1578 v = vec[str]()
1579 v = append(v, s)
1580 _, rv = pop(v)
1581 return rv
1582
1583 [file other.py]
1584 from native import call_append
1585
1586 def test_append() -> None:
1587 assert call_append("test123") == "test123"
1588
1589 [file driver.py]
1590 from other import test_append
1591
1592 test_append()
1593
1594 [case testIndirectLibrtDependency_experimental_librt]
1595 # Test that a compiled file (other.py) that indirectly depends on librt can import another compiled
1596 # file (native.py) that directly depends on it.
1597 from librt.strings import BytesWriter, write_i16_le
1598 from librt.vecs import vec, append, pop
1599 from mypy_extensions import i64
1600
1601 glob_bw = BytesWriter()
1602 glob_vec = vec[str](["one", "two", "three"])
1603
1604 def fn_returns_bw(b: bytes) -> BytesWriter:
1605 w = BytesWriter()
1606 w.write(b)
1607 return w
1608
1609 def fn_returns_vec(i: i64) -> vec[i64]:
1610 v = vec[i64]()
1611 v = append(v, i)
1612 return v
1613
1614 class ClassWithLibrtTypeMember:
1615 def __init__(self, w: BytesWriter, v: vec[str]) -> None:
1616 self.writer = w
1617 self.vec = vec[vec[str]]([v])
1618
1619 def method_returns_bw(self) -> BytesWriter:
1620 return self.writer
1621
1622 def method_returns_vec(self) -> vec[vec[str]]:
1623 return self.vec
1624
1625 [file other.py]
1626 import struct
1627
1628 from native import (
1629 glob_bw, glob_vec, fn_returns_bw, fn_returns_vec, ClassWithLibrtTypeMember, write_i16_le, pop
1630 )
1631 from mypy_extensions import i64
1632
1633 def test_global(b: bytes) -> None:
1634 glob_bw.write(b)
1635 assert glob_bw.getvalue() == b
1636
1637 glob_vec[1] = "not two"
1638 assert glob_vec[1] == "not two"
1639
1640 def test_fn(b: bytes, i: i64) -> None:
1641 assert fn_returns_bw(b).getvalue() == b
1642 assert fn_returns_vec(i)[0] == i
1643
1644 def test_class(b: bytes) -> None:
1645 c = ClassWithLibrtTypeMember(glob_bw, glob_vec)
1646 assert c.method_returns_bw().getvalue() == b
1647 assert c.method_returns_vec()[0] == glob_vec
1648
1649 def test_reexport() -> None:
1650 write_i16_le(glob_bw, 42)
1651 assert glob_bw.getvalue()[-2:] == struct.pack("<h", 42)
1652
1653 glob_vec, s = pop(glob_vec)
1654 assert len(glob_vec) == 2
1655 assert s == "three"
1656
1657 [file driver.py]
1658 from other import test_global, test_fn, test_class, test_reexport
1659
1660 input = b'x' * 512
1661 test_global(input)
1662 test_fn(input, 512)
1663 test_class(input)
1664 test_reexport()
1665
1666 [case testLibrtInternalInImportedFile_librt_internal]
1667 from librt.internal import ReadBuffer, WriteBuffer, write_str, read_str, cache_version
1668
1669 def get_buffer_round_trip_result(s: str) -> str:
1670 assert cache_version() == 0
1671 w = WriteBuffer()
1672 write_str(w, s)
1673 r = ReadBuffer(w.getvalue())
1674 return read_str(r)
1675
1676 [file other.py]
1677 from native import get_buffer_round_trip_result
1678
1679 def test_buffer_round_trip() -> None:
1680 assert get_buffer_round_trip_result("foo") == "foo"
1681
1682 [file driver.py]
1683 from other import test_buffer_round_trip
1684
1685 test_buffer_round_trip()
1686
1687 -- Regression tests for separate=True compilation.
1688
1689 [case testSeparateCrossGroupEnumMethod]
1690 -- Under separate=True, methods of non-extension classes (like Enum subclasses)
1691 -- are compiled as direct C functions rather than vtable entries.
1692 -- `is_method_final` must short-circuit to True for non-ext classes so the
1693 -- cross-group call site emits a direct call rather than indexing into a
1694 -- vtable that `compute_vtable` skipped.
1695 from other_enum import Color
1696
1697 def name_of_red() -> str:
1698 return Color.RED.describe()
1699
1700 def name_of_blue() -> str:
1701 return Color.BLUE.describe()
1702
1703 [file other_enum.py]
1704 from enum import Enum
1705
1706 class Color(Enum):
1707 RED = 1
1708 BLUE = 2
1709
1710 def describe(self) -> str:
1711 return "color:" + self.name
1712
1713 [file driver.py]
1714 from native import name_of_red, name_of_blue
1715 assert name_of_red() == "color:RED"
1716 assert name_of_blue() == "color:BLUE"
1717
1718 [case testSeparateCrossGroupGenerator]
1719 -- Under separate=True, mypyc-generated generator helper classes have their
1720 -- FuncIR bodies in the defining group; consumers only see FuncDecl via
1721 -- `method_decls`. `emit_method_call` must use `method_decl(name)` rather
1722 -- than asserting `get_method(name).decl` is non-None.
1723 from other_gen import count_up
1724
1725 def sum_range(n: int) -> int:
1726 total = 0
1727 for x in count_up(n):
1728 total += x
1729 return total
1730
1731 [file other_gen.py]
1732 from typing import Iterator
1733
1734 def count_up(n: int) -> Iterator[int]:
1735 i = 0
1736 while i < n:
1737 yield i
1738 i += 1
1739
1740 [file driver.py]
1741 from native import sum_range
1742 assert sum_range(0) == 0
1743 assert sum_range(1) == 0
1744 assert sum_range(5) == 10
1745
1746 [case testPackageCycleInheritedEq]
1747 -- Regression test for generating __ne__ from an inherited __eq__ when the
1748 -- inherited method's declaration is available before its FuncIR body has been
1749 -- generated. This can happen in package import cycles where __init__ imports a
1750 -- child module before the subpackage that defines the base class.
1751 from other.other_child import Child
1752
1753 def make_child() -> Child:
1754 return Child()
1755
1756 [file other/__init__.py]
1757 from other.other_child import Child as Child
1758 from other.other_subpkg import Base as Base
1759
1760 [file other/other_child.py]
1761 from other.other_subpkg import Base
1762
1763 class Child(Base):
1764 pass
1765
1766 [file other/other_subpkg/__init__.py]
1767 from other.other_subpkg.other_base import Base as Base
1768
1769 [file other/other_subpkg/other_base.py]
1770 class Base:
1771 def __eq__(self, other: object) -> bool:
1772 return True
1773
1774 [file driver.py]
1775 from native import make_child
1776 left = make_child()
1777 right = make_child()
1778 assert left == right
1779 assert not (left != right)
1780
1781 [case testSeparateCrossGroupInheritedInit]
1782 -- Under separate=True, a subclass whose __init__ is inherited from a
1783 -- different group must call the base's CPyPy_ wrapper through the exports
1784 -- table. This exercises `wrapper_function_call` in `generate_init_for_class`
1785 -- / `emit_setup_or_dunder_new_call`, and requires the CPyPy_ wrapper decl
1786 -- to be marked `needs_export=True` so it reaches the exports table.
1787 from other_base import Base
1788
1789 class Child(Base):
1790 def label(self) -> str:
1791 return "child(" + str(self.x) + ")"
1792
1793 def make_child(n: int) -> str:
1794 return Child(n).label()
1795
1796 [file other_base.py]
1797 class Base:
1798 def __init__(self, x: int) -> None:
1799 self.x = x
1800
1801 [file driver.py]
1802 from native import make_child
1803 assert make_child(7) == "child(7)"
1804 assert make_child(-1) == "child(-1)"
1805
1806 [case testIncrementalBuiltinBaseClassConstruction]
1807 # Regression: builtin_base classes (Exception subclasses) were unconditionally
1808 # added to func_to_decl in load_type_map, causing cross-group call sites to
1809 # emit CPyDef instead of CPyType for the constructor.
1810 from other_errors import MyError
1811 from other_util import process
1812
1813 def run(value: str) -> None:
1814 if not value:
1815 raise MyError("empty")
1816
1817 def compute(x: str) -> str:
1818 result = process(x)
1819 if not result:
1820 raise MyError("no result")
1821 return result
1822
1823 [file other_errors.py]
1824 class MyError(Exception):
1825 pass
1826
1827 [file other_util.py]
1828 def process(x: str) -> str:
1829 return x
1830
1831 [file other_util.py.2]
1832 def process(x: str, flag: bool = False) -> str:
1833 return x.strip()
1834
1835 [file driver.py]
1836 from native import run, compute
1837 try:
1838 run("")
1839 except Exception as e:
1840 print(str(e))
1841 print(compute("hello"))
1842
1843 [out]
1844 empty
1845 hello
1846 [out2]
1847 empty
1848 hello
1849
1850 [case testIncrementalCrossModuleInheritedAttrDefaultsWithOverride]
1851 # Regression: same shape as testIncrementalCrossModuleInheritedAttrDefaults,
1852 # but the subclass adds an attribute of its own, so generate_attr_defaults_init
1853 # emits a __mypyc_defaults_setup for it. Before the fix, the recompiled
1854 # subclass walked the parent's ClassDef.defs.body to collect inherited
1855 # defaults; when the parent was loaded from mypy's incremental cache that
1856 # body was empty, so the inherited initialization was dropped and any
1857 # access to an inherited attribute through compiled code raised
1858 # "AttributeError: attribute '<name>' of '<base>' undefined".
1859 import other_a
1860
1861 def test() -> None:
1862 c = other_a.Child()
1863 # Inherited attributes must still be initialized after the subclass
1864 # has been recompiled against a cache-loaded parent.
1865 assert c.x == 1
1866 assert c.y == "hello"
1867 # Own override is set by the subclass's own __mypyc_defaults_setup.
1868 assert c.z is True
1869 # Method defined on the parent reads an inherited attribute through
1870 # the compiled path; this is what crashes pre-fix.
1871 assert c.use() == 1
1872
1873 [file other_b.py]
1874 class Parent:
1875 x: int = 1
1876 y: str = "hello"
1877 z: bool = False
1878
1879 def use(self) -> int:
1880 if self.x:
1881 return 1
1882 return 0
1883
1884 [file other_a.py]
1885 from other_b import Parent
1886
1887 class Child(Parent):
1888 z: bool = True
1889
1890 [file other_a.py.2]
1891 from other_b import Parent
1892
1893 class Child(Parent):
1894 z: bool = True
1895
1896 def _force_recompile() -> int:
1897 return 1
1898
1899 [file driver.py]
1900 from native import test
1901 test()
1902
1903 [case testCrossModuleInheritedAttrDefaultsSameGroup]
1904 # separate: [(["native.py"], "grp1"), (["other_a.py", "other_b.py"], "grp2")]
1905 # Regression: with the subclass (other_a) and base (other_b) in the same
1906 # compilation group, IR build runs alphabetically within the group, so
1907 # the subclass is IR-built before the base. The decision to emit
1908 # __mypyc_defaults_setup (and a chained call to the ancestor's) must be
1909 # set up in the prepare phase, before any IR build runs; otherwise the
1910 # subclass's lookup of the parent's setup decl misses and inherited
1911 # defaults are lost on a fresh build.
1912 import other_a
1913
1914 def test() -> None:
1915 c = other_a.Child()
1916 assert c.x == 1
1917 assert c.z is True
1918
1919 [file other_b.py]
1920 class Parent:
1921 x: int = 1
1922
1923 [file other_a.py]
1924 from other_b import Parent
1925
1926 class Child(Parent):
1927 z: bool = True
1928
1929 [file driver.py]
1930 from native import test
1931 test()