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 [case testSeparateCompilationWithUndefinedAttribute]
1250 from other_a import A
1251
1252 def f() -> None:
1253 a = A()
1254 if a.x == 5:
1255 print(a.y)
1256 print(a.m())
1257 else:
1258 assert a.x == 6
1259 try:
1260 print(a.y)
1261 except AttributeError:
1262 print('y undefined')
1263 else:
1264 assert False
1265
1266 try:
1267 print(a.m())
1268 except AttributeError:
1269 print('y undefined')
1270 else:
1271 assert False
1272
1273 [file other_a.py]
1274 from other_b import B
1275
1276 class A(B):
1277 def __init__(self) -> None:
1278 self.y = 9
1279
1280 [file other_a.py.2]
1281 from other_b import B
1282
1283 class A(B):
1284 x = 6
1285
1286 def __init__(self) -> None:
1287 pass
1288
1289 [file other_b.py]
1290 class B:
1291 x = 5
1292
1293 def __init__(self) -> None:
1294 self.y = 7
1295
1296 def m(self) -> int:
1297 return self.y
1298
1299 [file driver.py]
1300 from native import f
1301 f()
1302
1303 [rechecked native, other_a]
1304
1305 [out]
1306 9
1307 9
1308 [out2]
1309 y undefined
1310 y undefined
1311
1312 [case testIncrementalCompilationWithDeletable]
1313 import other_a
1314 [file other_a.py]
1315 from other_b import C
1316 [file other_a.py.2]
1317 from other_b import C
1318 c = C()
1319 print(getattr(c, 'x', None))
1320 del c.x
1321 print(getattr(c, 'x', None))
1322 [file other_b.py]
1323 class C:
1324 __deletable__ = ['x']
1325 def __init__(self) -> None:
1326 self.x = 0
1327 [file driver.py]
1328 import native
1329 [out]
1330 [out2]
1331 0
1332 None
1333
1334 [case testIncrementalCompilationWithNonClassTypeDef]
1335 import other_a
1336 [file other_a.py]
1337 from other_b import MyInt
1338 [file other_a.py.2]
1339 from other_b import MyInt, NT, TD
1340 i = MyInt(42)
1341
1342 def f(x: MyInt) -> int:
1343 return x + 1
1344
1345 def g(x: int) -> MyInt:
1346 return MyInt(x + 2)
1347
1348 print(i)
1349 print(f(i))
1350 print(g(13))
1351
1352 def make_nt(x: int) -> NT:
1353 return NT(x=MyInt(x))
1354
1355 print(make_nt(4))
1356
1357 def make_td(x: int) -> TD:
1358 return {"x": MyInt(x)}
1359
1360 print(make_td(5))
1361
1362 [file other_b.py]
1363 from typing import NewType, NamedTuple, TypedDict
1364 from enum import Enum
1365
1366 MyInt = NewType("MyInt", int)
1367 NT = NamedTuple("NT", [("x", MyInt)])
1368 TD = TypedDict("TD", {"x": MyInt})
1369
1370 [file driver.py]
1371 import native
1372
1373 [typing fixtures/typing-full.pyi]
1374 [out]
1375 [out2]
1376 42
1377 43
1378 15
1379 NT(x=4)
1380 {'x': 5}
1381
1382 [case testExtraLibRtSourceFileDep]
1383 table_list = list(range(256))
1384 table_list[ord('A')] = ord('B')
1385 table = bytes(table_list)
1386
1387 def translate(b: bytes) -> bytes:
1388 # The primimitive for bytes.translate requires an optional C file from lib-rt
1389 return b.translate(table)
1390 [file driver.py]
1391 import native
1392 assert native.translate(b'ABCD') == b'BBCD'
1393
1394 [case testIncrementalCrossGroupExportTableOffsets]
1395 # Regression: under separate=True, each consumer module's IR is
1396 # compiled against the positional layout of its deps'
1397 # `exports_<group>` struct. Reordering the dep's classes keeps the
1398 # same set of public names, so mypy's interface hash for the dep is
1399 # unchanged -- the consumer is not invalidated and stays fully
1400 # cached, which causes `_load_cached_group_files` to return empty
1401 # cfile content for the consumer's group.
1402 #
1403 # Before the fix, `get_header_deps` over empty content returned no
1404 # includes, so `Extension.depends` for the consumer ended up empty
1405 # and setuptools never recompiled the consumer's .o when the dep's
1406 # `__native_<dep>.h` shifted struct offsets. The stale .o kept the
1407 # old offsets and silently resolved cross-group calls to the wrong
1408 # class.
1409 from other_classes import Gamma, Delta
1410
1411 def make_gamma() -> Gamma:
1412 return Gamma()
1413
1414 def make_delta() -> Delta:
1415 return Delta()
1416
1417 [file other_classes.py]
1418 class Alpha:
1419 a: int = 1
1420
1421 class Beta:
1422 b: int = 2
1423
1424 class Gamma:
1425 g: int = 3
1426
1427 class Delta:
1428 d: int = 4
1429
1430 [file other_classes.py.2]
1431 class Delta:
1432 d: int = 4
1433
1434 class Alpha:
1435 a: int = 1
1436
1437 class Beta:
1438 b: int = 2
1439
1440 class Gamma:
1441 g: int = 3
1442
1443 [file driver.py]
1444 import native
1445 assert type(native.make_gamma()).__name__ == "Gamma"
1446 assert type(native.make_delta()).__name__ == "Delta"
1447
1448 [case testCrossModuleAttrDefaults]
1449 from other import Parent
1450
1451 class Child(Parent):
1452 extra: int = 99
1453
1454 def test() -> None:
1455 c = Child()
1456 assert c.config == {"key": "value"}
1457 assert c.extra == 99
1458 assert c.total == 60
1459 p = Parent()
1460 assert p.config == {"key": "value"}
1461 assert p.total == 60
1462 assert Parent.TAG == "parent"
1463
1464 [file other.py]
1465 from typing import ClassVar, Dict
1466 MY_DEFAULT: Dict[str, str] = {"key": "value"}
1467 VAL_1: int = 10
1468 VAL_2: int = 20
1469 VAL_3: int = 30
1470
1471 class Parent:
1472 config: Dict[str, str] = MY_DEFAULT
1473 total: int = VAL_1 + VAL_2 + VAL_3
1474 TAG: ClassVar[str] = "parent"
1475
1476 [file driver.py]
1477 from native import test
1478 test()
1479
1480 [case testIncrementalCrossModuleInheritedAttrDefaults]
1481 # Regression: under separate=True, when only the subclass module is
1482 # recompiled (parent loaded from mypy's incremental cache, so its
1483 # ClassDef.defs.body is empty), the subclass produces no
1484 # __mypyc_defaults_setup of its own and ClassIR.get_method returns
1485 # the parent's. The emitted call must use the cross-group
1486 # exports_<group>. prefix, otherwise the generated C references an
1487 # undeclared symbol and clang/gcc fail to compile.
1488 import other_a
1489
1490 def test() -> None:
1491 c = other_a.Child()
1492 assert c.x == 1
1493 assert c.y == "hello"
1494
1495 [file other_b.py]
1496 class Parent:
1497 x: int = 1
1498 y: str = "hello"
1499
1500 [file other_a.py]
1501 from other_b import Parent
1502
1503 class Child(Parent):
1504 pass
1505
1506 [file other_a.py.2]
1507 from other_b import Parent
1508
1509 class Child(Parent):
1510 pass
1511
1512 def _force_recompile() -> int:
1513 return 1
1514
1515 [file driver.py]
1516 from native import test
1517 test()
1518
1519 [case testExtraOpsFunction_experimental_librt]
1520 from librt.strings import BytesWriter
1521
1522 def call_write(b: bytes) -> bytes:
1523 w = BytesWriter()
1524 w.write(b) # calls CPyBytesWriter_Write defined in byteswriter_extra_ops.c
1525 return w.getvalue()
1526
1527 [file other.py]
1528 from native import call_write
1529
1530 def test(b: bytes) -> bytes:
1531 return call_write(b)
1532
1533 [file driver.py]
1534 from other import test
1535
1536 input = b'x' * 512
1537 assert test(input) == input
1538
1539 [case testLibrtDependencyInImportedFile_experimental_librt]
1540 # Test that a compiled file (other.py) that does not depend on librt can import another compiled
1541 # file (native.py) that does.
1542 from librt.vecs import vec, append, pop
1543
1544 def call_append(s: str) -> str:
1545 v = vec[str]()
1546 v = append(v, s)
1547 _, rv = pop(v)
1548 return rv
1549
1550 [file other.py]
1551 from native import call_append
1552
1553 def test_append() -> None:
1554 assert call_append("test123") == "test123"
1555
1556 [file driver.py]
1557 from other import test_append
1558
1559 test_append()
1560
1561 [case testIndirectLibrtDependency_experimental_librt]
1562 # Test that a compiled file (other.py) that indirectly depends on librt can import another compiled
1563 # file (native.py) that directly depends on it.
1564 from librt.strings import BytesWriter, write_i16_le
1565 from librt.vecs import vec, append, pop
1566 from mypy_extensions import i64
1567
1568 glob_bw = BytesWriter()
1569 glob_vec = vec[str](["one", "two", "three"])
1570
1571 def fn_returns_bw(b: bytes) -> BytesWriter:
1572 w = BytesWriter()
1573 w.write(b)
1574 return w
1575
1576 def fn_returns_vec(i: i64) -> vec[i64]:
1577 v = vec[i64]()
1578 v = append(v, i)
1579 return v
1580
1581 class ClassWithLibrtTypeMember:
1582 def __init__(self, w: BytesWriter, v: vec[str]) -> None:
1583 self.writer = w
1584 self.vec = vec[vec[str]]([v])
1585
1586 def method_returns_bw(self) -> BytesWriter:
1587 return self.writer
1588
1589 def method_returns_vec(self) -> vec[vec[str]]:
1590 return self.vec
1591
1592 [file other.py]
1593 import struct
1594
1595 from native import (
1596 glob_bw, glob_vec, fn_returns_bw, fn_returns_vec, ClassWithLibrtTypeMember, write_i16_le, pop
1597 )
1598 from mypy_extensions import i64
1599
1600 def test_global(b: bytes) -> None:
1601 glob_bw.write(b)
1602 assert glob_bw.getvalue() == b
1603
1604 glob_vec[1] = "not two"
1605 assert glob_vec[1] == "not two"
1606
1607 def test_fn(b: bytes, i: i64) -> None:
1608 assert fn_returns_bw(b).getvalue() == b
1609 assert fn_returns_vec(i)[0] == i
1610
1611 def test_class(b: bytes) -> None:
1612 c = ClassWithLibrtTypeMember(glob_bw, glob_vec)
1613 assert c.method_returns_bw().getvalue() == b
1614 assert c.method_returns_vec()[0] == glob_vec
1615
1616 def test_reexport() -> None:
1617 write_i16_le(glob_bw, 42)
1618 assert glob_bw.getvalue()[-2:] == struct.pack("<h", 42)
1619
1620 glob_vec, s = pop(glob_vec)
1621 assert len(glob_vec) == 2
1622 assert s == "three"
1623
1624 [file driver.py]
1625 from other import test_global, test_fn, test_class, test_reexport
1626
1627 input = b'x' * 512
1628 test_global(input)
1629 test_fn(input, 512)
1630 test_class(input)
1631 test_reexport()
1632
1633 [case testLibrtInternalInImportedFile_librt_internal]
1634 from librt.internal import ReadBuffer, WriteBuffer, write_str, read_str, cache_version
1635
1636 def get_buffer_round_trip_result(s: str) -> str:
1637 assert cache_version() == 0
1638 w = WriteBuffer()
1639 write_str(w, s)
1640 r = ReadBuffer(w.getvalue())
1641 return read_str(r)
1642
1643 [file other.py]
1644 from native import get_buffer_round_trip_result
1645
1646 def test_buffer_round_trip() -> None:
1647 assert get_buffer_round_trip_result("foo") == "foo"
1648
1649 [file driver.py]
1650 from other import test_buffer_round_trip
1651
1652 test_buffer_round_trip()
1653
1654 -- Regression tests for separate=True compilation.
1655
1656 [case testSeparateCrossGroupEnumMethod]
1657 -- Under separate=True, methods of non-extension classes (like Enum subclasses)
1658 -- are compiled as direct C functions rather than vtable entries.
1659 -- `is_method_final` must short-circuit to True for non-ext classes so the
1660 -- cross-group call site emits a direct call rather than indexing into a
1661 -- vtable that `compute_vtable` skipped.
1662 from other_enum import Color
1663
1664 def name_of_red() -> str:
1665 return Color.RED.describe()
1666
1667 def name_of_blue() -> str:
1668 return Color.BLUE.describe()
1669
1670 [file other_enum.py]
1671 from enum import Enum
1672
1673 class Color(Enum):
1674 RED = 1
1675 BLUE = 2
1676
1677 def describe(self) -> str:
1678 return "color:" + self.name
1679
1680 [file driver.py]
1681 from native import name_of_red, name_of_blue
1682 assert name_of_red() == "color:RED"
1683 assert name_of_blue() == "color:BLUE"
1684
1685 [case testSeparateCrossGroupGenerator]
1686 -- Under separate=True, mypyc-generated generator helper classes have their
1687 -- FuncIR bodies in the defining group; consumers only see FuncDecl via
1688 -- `method_decls`. `emit_method_call` must use `method_decl(name)` rather
1689 -- than asserting `get_method(name).decl` is non-None.
1690 from other_gen import count_up
1691
1692 def sum_range(n: int) -> int:
1693 total = 0
1694 for x in count_up(n):
1695 total += x
1696 return total
1697
1698 [file other_gen.py]
1699 from typing import Iterator
1700
1701 def count_up(n: int) -> Iterator[int]:
1702 i = 0
1703 while i < n:
1704 yield i
1705 i += 1
1706
1707 [file driver.py]
1708 from native import sum_range
1709 assert sum_range(0) == 0
1710 assert sum_range(1) == 0
1711 assert sum_range(5) == 10
1712
1713 [case testPackageCycleInheritedEq]
1714 -- Regression test for generating __ne__ from an inherited __eq__ when the
1715 -- inherited method's declaration is available before its FuncIR body has been
1716 -- generated. This can happen in package import cycles where __init__ imports a
1717 -- child module before the subpackage that defines the base class.
1718 from other.other_child import Child
1719
1720 def make_child() -> Child:
1721 return Child()
1722
1723 [file other/__init__.py]
1724 from other.other_child import Child as Child
1725 from other.other_subpkg import Base as Base
1726
1727 [file other/other_child.py]
1728 from other.other_subpkg import Base
1729
1730 class Child(Base):
1731 pass
1732
1733 [file other/other_subpkg/__init__.py]
1734 from other.other_subpkg.other_base import Base as Base
1735
1736 [file other/other_subpkg/other_base.py]
1737 class Base:
1738 def __eq__(self, other: object) -> bool:
1739 return True
1740
1741 [file driver.py]
1742 from native import make_child
1743 left = make_child()
1744 right = make_child()
1745 assert left == right
1746 assert not (left != right)
1747
1748 [case testSeparateCrossGroupInheritedInit]
1749 -- Under separate=True, a subclass whose __init__ is inherited from a
1750 -- different group must call the base's CPyPy_ wrapper through the exports
1751 -- table. This exercises `wrapper_function_call` in `generate_init_for_class`
1752 -- / `emit_setup_or_dunder_new_call`, and requires the CPyPy_ wrapper decl
1753 -- to be marked `needs_export=True` so it reaches the exports table.
1754 from other_base import Base
1755
1756 class Child(Base):
1757 def label(self) -> str:
1758 return "child(" + str(self.x) + ")"
1759
1760 def make_child(n: int) -> str:
1761 return Child(n).label()
1762
1763 [file other_base.py]
1764 class Base:
1765 def __init__(self, x: int) -> None:
1766 self.x = x
1767
1768 [file driver.py]
1769 from native import make_child
1770 assert make_child(7) == "child(7)"
1771 assert make_child(-1) == "child(-1)"
1772
1773 [case testIncrementalBuiltinBaseClassConstruction]
1774 # Regression: builtin_base classes (Exception subclasses) were unconditionally
1775 # added to func_to_decl in load_type_map, causing cross-group call sites to
1776 # emit CPyDef instead of CPyType for the constructor.
1777 from other_errors import MyError
1778 from other_util import process
1779
1780 def run(value: str) -> None:
1781 if not value:
1782 raise MyError("empty")
1783
1784 def compute(x: str) -> str:
1785 result = process(x)
1786 if not result:
1787 raise MyError("no result")
1788 return result
1789
1790 [file other_errors.py]
1791 class MyError(Exception):
1792 pass
1793
1794 [file other_util.py]
1795 def process(x: str) -> str:
1796 return x
1797
1798 [file other_util.py.2]
1799 def process(x: str, flag: bool = False) -> str:
1800 return x.strip()
1801
1802 [file driver.py]
1803 from native import run, compute
1804 try:
1805 run("")
1806 except Exception as e:
1807 print(str(e))
1808 print(compute("hello"))
1809
1810 [out]
1811 empty
1812 hello
1813 [out2]
1814 empty
1815 hello
1816
1817 [case testIncrementalCrossModuleInheritedAttrDefaultsWithOverride]
1818 # Regression: same shape as testIncrementalCrossModuleInheritedAttrDefaults,
1819 # but the subclass adds an attribute of its own, so generate_attr_defaults_init
1820 # emits a __mypyc_defaults_setup for it. Before the fix, the recompiled
1821 # subclass walked the parent's ClassDef.defs.body to collect inherited
1822 # defaults; when the parent was loaded from mypy's incremental cache that
1823 # body was empty, so the inherited initialization was dropped and any
1824 # access to an inherited attribute through compiled code raised
1825 # "AttributeError: attribute '<name>' of '<base>' undefined".
1826 import other_a
1827
1828 def test() -> None:
1829 c = other_a.Child()
1830 # Inherited attributes must still be initialized after the subclass
1831 # has been recompiled against a cache-loaded parent.
1832 assert c.x == 1
1833 assert c.y == "hello"
1834 # Own override is set by the subclass's own __mypyc_defaults_setup.
1835 assert c.z is True
1836 # Method defined on the parent reads an inherited attribute through
1837 # the compiled path; this is what crashes pre-fix.
1838 assert c.use() == 1
1839
1840 [file other_b.py]
1841 class Parent:
1842 x: int = 1
1843 y: str = "hello"
1844 z: bool = False
1845
1846 def use(self) -> int:
1847 if self.x:
1848 return 1
1849 return 0
1850
1851 [file other_a.py]
1852 from other_b import Parent
1853
1854 class Child(Parent):
1855 z: bool = True
1856
1857 [file other_a.py.2]
1858 from other_b import Parent
1859
1860 class Child(Parent):
1861 z: bool = True
1862
1863 def _force_recompile() -> int:
1864 return 1
1865
1866 [file driver.py]
1867 from native import test
1868 test()
1869
1870 [case testCrossModuleInheritedAttrDefaultsSameGroup]
1871 # separate: [(["native.py"], "grp1"), (["other_a.py", "other_b.py"], "grp2")]
1872 # Regression: with the subclass (other_a) and base (other_b) in the same
1873 # compilation group, IR build runs alphabetically within the group, so
1874 # the subclass is IR-built before the base. The decision to emit
1875 # __mypyc_defaults_setup (and a chained call to the ancestor's) must be
1876 # set up in the prepare phase, before any IR build runs; otherwise the
1877 # subclass's lookup of the parent's setup decl misses and inherited
1878 # defaults are lost on a fresh build.
1879 import other_a
1880
1881 def test() -> None:
1882 c = other_a.Child()
1883 assert c.x == 1
1884 assert c.z is True
1885
1886 [file other_b.py]
1887 class Parent:
1888 x: int = 1
1889
1890 [file other_a.py]
1891 from other_b import Parent
1892
1893 class Child(Parent):
1894 z: bool = True
1895
1896 [file driver.py]
1897 from native import test
1898 test()