| -- These test cases compile two or more modules at a time. | |
| -- Any file prefixed with "other" is compiled. | |
| -- | |
| -- Note that these are run in three compilation modes: regular, | |
| -- multi-file and separate. See the docstrings of | |
| -- mypyc.test.test_run.TestRunMultiFile and | |
| -- mypyc.test.test_run.TestRunSeparate for more information. | |
| -- | |
| -- Some of these files perform multiple incremental runs. See | |
| -- test-data/unit/check-incremental.test for more information | |
| -- about how this is specified (e.g. .2 file name suffixes). | |
| [case testMultiModulePackage] | |
| from p.other import g, _i as i | |
| def f(x: int) -> int: | |
| from p.other import h | |
| return i(h(g(x + 1))) | |
| [file p/__init__.py] | |
| [file p/other.py] | |
| def g(x: int) -> int: | |
| return x + 2 | |
| def h(x: int) -> int: | |
| return x + 1 | |
| def _i(x: int) -> int: | |
| return x + 3 | |
| [file driver.py] | |
| import native | |
| from native import f | |
| from p.other import g | |
| assert f(3) == 10 | |
| assert g(2) == 4 | |
| try: | |
| f(1.1) | |
| except TypeError: | |
| pass | |
| else: | |
| assert False | |
| try: | |
| g(1.1) | |
| except TypeError: | |
| pass | |
| else: | |
| assert False | |
| [case testImportNonNativeSubmoduleFrom] | |
| # separate: [(["native.py", "other_pkg/__init__.py"], "testgroup")] | |
| import types | |
| from other_pkg import helper | |
| def f() -> int: | |
| return helper.func() | |
| def g() -> types.ModuleType: | |
| return helper | |
| [file other_pkg/__init__.py] | |
| [file other_pkg/helper.py] | |
| def func() -> int: | |
| return 42 | |
| [file driver.py] | |
| from native import f, g | |
| import other_pkg.helper | |
| assert f() == 42 | |
| assert g() is other_pkg.helper | |
| [case testNativeSubmoduleOfNonNativePackageFrom] | |
| # separate: [(["native.py", "pkg/other_mod.py"], "testgroup")] | |
| from pkg import other_mod | |
| def f() -> int: | |
| return other_mod.func() | |
| [file pkg/__init__.py] | |
| [file pkg/other_mod.py] | |
| def func() -> int: | |
| return 42 | |
| [file driver.py] | |
| import importlib.machinery | |
| import os | |
| import native | |
| import pkg.other_mod | |
| assert native.f() == 42 | |
| # other_mod should be in native's namespace and be the same object as pkg.other_mod | |
| assert native.other_mod is pkg.other_mod | |
| # native-to-native import should preserve module metadata such as __file__ | |
| ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES | |
| assert any(native.other_mod.__file__.endswith(s) for s in ext_suffixes), native.other_mod.__file__ | |
| # The directory of __file__ should reflect the package structure relative to the root | |
| root_dir = os.path.dirname(native.__file__) | |
| assert os.path.dirname(native.other_mod.__file__) == os.path.join(root_dir, "pkg"), \ | |
| native.other_mod.__file__ | |
| [case testNativeSubmoduleOfNativePackageFrom] | |
| # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")] | |
| from other_pkg import other_sub | |
| def f() -> int: | |
| return other_sub.func() | |
| [file other_pkg/__init__.py] | |
| [file other_pkg/other_sub.py] | |
| def func() -> int: | |
| return 42 | |
| [file driver.py] | |
| import importlib.machinery | |
| import os | |
| import native | |
| import other_pkg.other_sub | |
| assert native.f() == 42 | |
| assert native.other_sub is other_pkg.other_sub | |
| # Fast path import should preserve __file__ as a proper extension path | |
| ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES | |
| assert any(native.other_sub.__file__.endswith(s) for s in ext_suffixes), native.other_sub.__file__ | |
| # The directory of __file__ should reflect the package structure relative to the root | |
| root_dir = os.path.dirname(native.__file__) | |
| assert os.path.dirname(native.other_sub.__file__) == os.path.join(root_dir, "other_pkg"), \ | |
| native.other_sub.__file__ | |
| [case testImportFromBucketingEndToEnd] | |
| # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")] | |
| from other_pkg import other_sub as sub_alias, other_attr as attr_alias, py_sub as py_alias | |
| [file other_pkg/__init__.py] | |
| other_attr = 41 | |
| [file other_pkg/other_sub.py] | |
| def func() -> int: | |
| return 10 | |
| [file other_pkg/py_sub.py] | |
| def func() -> int: | |
| return 20 | |
| [file driver.py] | |
| import importlib | |
| import native | |
| other_sub = importlib.import_module("other_pkg.other_sub") | |
| py_sub = importlib.import_module("other_pkg.py_sub") | |
| assert native.sub_alias is other_sub | |
| assert native.attr_alias == 41 | |
| assert native.py_alias is py_sub | |
| assert native.sub_alias.func() == 10 | |
| assert native.py_alias.func() == 20 | |
| [case testNativeTopLevelModuleFileDir] | |
| # separate: [(["native.py", "other_top.py"], "testgroup")] | |
| import other_top | |
| def f() -> int: | |
| return other_top.func() | |
| [file other_top.py] | |
| def func() -> int: | |
| return 99 | |
| [file driver.py] | |
| import importlib.machinery | |
| import os | |
| import native | |
| import other_top | |
| assert native.f() == 99 | |
| # Top-level native module __file__ directory should match the shared lib's directory | |
| ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES | |
| assert any(other_top.__file__.endswith(s) for s in ext_suffixes), other_top.__file__ | |
| root_dir = os.path.dirname(native.__file__) | |
| assert os.path.dirname(other_top.__file__) == root_dir, other_top.__file__ | |
| [case testNativeDeeplyNestedSubmoduleFileDir] | |
| # separate: [(["native.py", "other_a/__init__.py", "other_a/other_b/__init__.py", "other_a/other_b/other_c.py"], "testgroup")] | |
| from other_a.other_b import other_c | |
| def f() -> int: | |
| return other_c.func() | |
| [file other_a/__init__.py] | |
| [file other_a/other_b/__init__.py] | |
| [file other_a/other_b/other_c.py] | |
| def func() -> int: | |
| return 77 | |
| [file driver.py] | |
| import importlib.machinery | |
| import os | |
| import native | |
| import other_a.other_b.other_c | |
| assert native.f() == 77 | |
| assert native.other_c is other_a.other_b.other_c | |
| # Deeply nested module __file__ should have correct extension suffix | |
| ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES | |
| assert any(native.other_c.__file__.endswith(s) for s in ext_suffixes), native.other_c.__file__ | |
| # The directory should reflect the full package hierarchy | |
| root_dir = os.path.dirname(native.__file__) | |
| expected_dir = os.path.join(root_dir, "other_a", "other_b") | |
| assert os.path.dirname(native.other_c.__file__) == expected_dir, native.other_c.__file__ | |
| [case testNativeImportPackageAttribute] | |
| # separate: [(["native.py", "other_top.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")] | |
| import other_top | |
| from other_pkg import other_sub | |
| import other_pkg | |
| def get_top() -> str: | |
| p = other_top.__package__ | |
| assert p is not None | |
| return p | |
| def get_sub() -> str: | |
| p = other_sub.__package__ | |
| assert p is not None | |
| return p | |
| def get_pkg() -> str: | |
| p = other_pkg.__package__ | |
| assert p is not None | |
| return p | |
| [file other_top.py] | |
| def func() -> int: | |
| return 1 | |
| [file other_pkg/__init__.py] | |
| [file other_pkg/other_sub.py] | |
| def func() -> int: | |
| return 2 | |
| [file driver.py] | |
| from native import get_top, get_sub, get_pkg | |
| # Top-level module: __package__ should be "" (empty string) | |
| assert get_top() == "", repr(get_top()) | |
| # Submodule: __package__ should be the parent package name | |
| assert get_sub() == "other_pkg", repr(get_sub()) | |
| # Package __init__: __package__ should be the package name itself | |
| assert get_pkg() == "other_pkg", repr(get_pkg()) | |
| [case testNativeImportFileAvailableAtInitTime] | |
| # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")] | |
| from other_pkg import other_sub | |
| def f() -> int: | |
| return other_sub.func() | |
| [file other_pkg/__init__.py] | |
| [file other_pkg/other_sub.py] | |
| # __file__ should be available during module initialization | |
| _file: str = __file__ | |
| def func() -> int: | |
| return 42 | |
| [file driver.py] | |
| import importlib.machinery | |
| import native | |
| assert native.f() == 42 | |
| # Verify that __file__ captured at init time has a valid extension suffix | |
| ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES | |
| assert any(native.other_sub._file.endswith(s) for s in ext_suffixes), native.other_sub._file | |
| [case testNativeImportPathAttribute] | |
| # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")] | |
| import other_pkg | |
| from other_pkg import other_sub | |
| def get_pkg_path() -> str: | |
| return other_pkg.__path__[0] | |
| def get_sub_has_path() -> bool: | |
| return hasattr(other_sub, '__path__') | |
| [file other_pkg/__init__.py] | |
| # __path__ should be available during package initialization | |
| _path: list[str] = __path__ | |
| [file other_pkg/other_sub.py] | |
| def func() -> int: | |
| return 1 | |
| [file driver.py] | |
| import os | |
| import native | |
| # Package should have __path__ set to [dirname(__file__)] | |
| expected = os.path.dirname(native.other_pkg.__file__) | |
| assert native.get_pkg_path() == expected, (native.get_pkg_path(), expected) | |
| # __path__ should have been accessible at init time | |
| assert native.other_pkg._path == [expected], native.other_pkg._path | |
| # Non-package submodule should NOT have __path__ | |
| assert not native.get_sub_has_path() | |
| [case testNativeImportPackageFileDirMatchesPath] | |
| # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")] | |
| import other_pkg | |
| from other_pkg import other_sub | |
| def get_pkg_file() -> str: | |
| return other_pkg.__file__ | |
| def get_pkg_path() -> str: | |
| return other_pkg.__path__[0] | |
| def get_sub_file() -> str: | |
| return other_sub.__file__ | |
| [file other_pkg/__init__.py] | |
| x = 1 | |
| [file other_pkg/other_sub.py] | |
| def func() -> int: | |
| return 1 | |
| [file driver.py] | |
| import os | |
| import native | |
| pkg_file = native.get_pkg_file() | |
| pkg_path = native.get_pkg_path() | |
| sub_file = native.get_sub_file() | |
| # Package __file__ should contain __init__ (e.g. other_pkg/__init__.cpython-312-x86_64-linux-gnu.so) | |
| assert "__init__" in os.path.basename(pkg_file), \ | |
| f"Package __file__ should contain __init__, got: {pkg_file}" | |
| # Package __path__ should be the directory containing the package's __init__ file | |
| assert pkg_path == os.path.dirname(pkg_file), \ | |
| f"__path__ ({pkg_path}) should equal dirname(__file__) ({os.path.dirname(pkg_file)})" | |
| # __path__ should end with the package name | |
| assert os.path.basename(pkg_path) == "other_pkg", \ | |
| f"__path__ should end with package name, got: {pkg_path}" | |
| # Submodule __file__ should be inside the package directory (i.e. inside __path__) | |
| assert os.path.dirname(sub_file) == pkg_path, \ | |
| f"Submodule dir ({os.path.dirname(sub_file)}) should equal package __path__ ({pkg_path})" | |
| [case testNativeImportSpecAttribute] | |
| # separate: [(["native.py", "other_top.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")] | |
| from typing import Any | |
| import other_top | |
| from other_pkg import other_sub | |
| import other_pkg | |
| def get_top_spec() -> Any: | |
| return other_top.__spec__ | |
| def get_sub_spec() -> Any: | |
| return other_sub.__spec__ | |
| def get_pkg_spec() -> Any: | |
| return other_pkg.__spec__ | |
| [file other_top.py] | |
| from typing import Any | |
| # __spec__ should be available during module initialization | |
| _spec: Any = __spec__ # type: ignore[name-defined] | |
| def func() -> int: | |
| return 1 | |
| [file other_pkg/__init__.py] | |
| [file other_pkg/other_sub.py] | |
| def func() -> int: | |
| return 2 | |
| [file driver.py] | |
| import importlib.machinery | |
| import native | |
| top_spec = native.get_top_spec() | |
| sub_spec = native.get_sub_spec() | |
| pkg_spec = native.get_pkg_spec() | |
| # __spec__.name should match the module name | |
| assert top_spec.name == "other_top" | |
| assert sub_spec.name == "other_pkg.other_sub" | |
| assert pkg_spec.name == "other_pkg" | |
| # __spec__ should have correct origin (same as __file__) | |
| assert top_spec.origin == native.other_top.__file__ | |
| assert sub_spec.origin == native.other_sub.__file__ | |
| # __spec__.loader should be an ExtensionFileLoader and also be set as __loader__ | |
| assert isinstance(top_spec.loader, importlib.machinery.ExtensionFileLoader) | |
| assert native.other_top.__loader__ is top_spec.loader | |
| # Package spec should have submodule_search_locations | |
| assert pkg_spec.submodule_search_locations is not None | |
| # Non-package spec should not have submodule_search_locations | |
| assert top_spec.submodule_search_locations is None | |
| # __spec__ should be available at init time | |
| assert native.other_top._spec.name == "other_top" | |
| [case testNativeSubmoduleFailureDoesNotBindParentEarly] | |
| # separate: [(["native.py", "other_pkg/__init__.py", "other_pkg/other_sub.py"], "testgroup")] | |
| from other_pkg import other_sub | |
| [file other_pkg/__init__.py] | |
| x = 1 | |
| [file other_pkg/other_sub.py] | |
| import other_pkg | |
| if hasattr(other_pkg, "other_sub"): | |
| raise RuntimeError("parent attr visible too early") | |
| raise RuntimeError("boom from other_sub") | |
| [file driver.py] | |
| import sys | |
| import other_pkg | |
| try: | |
| import native | |
| except RuntimeError as e: | |
| assert str(e) == "boom from other_sub" | |
| else: | |
| assert False, "import native should fail" | |
| assert not hasattr(other_pkg, "other_sub") | |
| assert "other_pkg.other_sub" not in sys.modules | |
| [case testNativeImportUsesExistingNativeSysModulesObject] | |
| # separate: [(["native.py", "other_top.py"], "testgroup")] | |
| import other_top | |
| def f() -> int: | |
| return other_top.value | |
| [file other_top.py] | |
| value = 42 | |
| [file driver.py] | |
| import native | |
| import other_top | |
| assert native.other_top is other_top | |
| assert native.f() == 42 | |
| [case testNativeImportRejectsForeignSysModulesObject] | |
| # separate: [(["native.py", "other_top.py"], "testgroup")] | |
| import other_top | |
| def f() -> int: | |
| return other_top.value | |
| [file other_top.py] | |
| value = 42 | |
| [file driver.py] | |
| import sys | |
| import types | |
| import other_top | |
| fake = types.ModuleType("other_top") | |
| fake.value = -1 | |
| sys.modules["other_top"] = fake | |
| try: | |
| import native | |
| except ImportError as e: | |
| assert "other_top" in str(e) | |
| assert "replaced after initialization" in str(e) | |
| else: | |
| assert False, "import native should fail" | |
| assert sys.modules["other_top"] is fake | |
| [case testNativeImportRejectsSysModulesReplacementDuringInitialization] | |
| # separate: [(["native.py", "other_target.py"], "testgroup")] | |
| def load_target() -> None: | |
| import other_target | |
| [file other_target.py] | |
| import sys | |
| replacement = object() | |
| sys.modules[__name__] = replacement | |
| [file sys/__init__.pyi] | |
| modules: dict[str, object] | |
| [file driver.py] | |
| import sys | |
| import native | |
| from testutil import assertRaises | |
| with assertRaises( | |
| ImportError, | |
| "native module 'other_target' in sys.modules was replaced after initialization", | |
| ): | |
| native.load_target() | |
| assert "other_target" not in sys.modules | |
| [case testNativeImportRejectsSysModulesRemovalDuringInitialization] | |
| # separate: [(["native.py", "other_target.py"], "testgroup")] | |
| def load_target() -> None: | |
| import other_target | |
| [file other_target.py] | |
| import sys | |
| del sys.modules[__name__] | |
| [file sys/__init__.pyi] | |
| modules: dict[str, object] | |
| [file driver.py] | |
| import sys | |
| import native | |
| from testutil import assertRaises | |
| with assertRaises( | |
| ImportError, | |
| "initialized native module 'other_target' is missing from sys.modules", | |
| ): | |
| native.load_target() | |
| assert "other_target" not in sys.modules | |
| [case testMultiModuleFastpaths] | |
| [file other_main.py] | |
| [file other_main.py.2] | |
| from other_b import A, func | |
| class B(A): | |
| pass | |
| def test() -> None: | |
| a = A() | |
| assert func() == 12 | |
| assert a.method() == "test" | |
| test() | |
| [file other_b.py] | |
| class A: | |
| def method(self) -> str: | |
| return "test" | |
| def func() -> int: | |
| return 12 | |
| # Remove all the methods and functions from globals to ensure that | |
| # they get called via the fastpaths even when doing incremental | |
| # compilation. | |
| setattr(A, 'method', None) | |
| setattr(A, '__init__', None) | |
| globals()['func'] = None | |
| globals()['A'] = None | |
| [file driver.py] | |
| import other_main | |
| [case testMultiModuleDecoratedMethodOverride] | |
| from typing import Any, Callable, TypeVar | |
| from other_base import Base, call_method | |
| F = TypeVar("F", bound=Callable[..., Any]) | |
| def add_ten(f: F) -> F: | |
| def wrapper(self: Any, x: int) -> int: | |
| return f(self, x) + 10 | |
| return wrapper # type: ignore[return-value] | |
| class Derived(Base): | |
| @add_ten | |
| def method(self, x: int) -> int: | |
| return x * 2 | |
| def test_decorated_override() -> None: | |
| d = Derived() | |
| assert d.method(1) == 12 | |
| assert call_method(d, 1) == 12 | |
| assert call_method(Base(), 1) == 1 | |
| [file other_base.py] | |
| class Base: | |
| def method(self, x: int) -> int: | |
| return x | |
| def call_method(b: Base, x: int) -> int: | |
| return b.method(x) | |
| [typing fixtures/typing-full.pyi] | |
| [case testMultiModuleWeakrefs] | |
| # Base classes are in a module that is prepared after this one (modules are | |
| # processed in name order), and in another group in separate compilation mode. | |
| import gc | |
| import weakref | |
| from typing import Any | |
| from mypy_extensions import mypyc_attr | |
| from other_base import WeakBase, ActionBase | |
| class Sub(WeakBase): | |
| def __init__(self) -> None: | |
| super().__init__() | |
| self.y = 2 | |
| # Redundant, but allowed | |
| @mypyc_attr(weakrefs=True) | |
| class ExplicitSub(Sub): | |
| pass | |
| class ActionSub(ActionBase): | |
| def __init__(self) -> None: | |
| super().__init__() | |
| self.y = 2 | |
| def check(cls: Any) -> None: | |
| objs = [cls() for i in range(100)] | |
| refs = [weakref.ref(o) for o in objs] | |
| assert objs[0].x == 1 and objs[0].y == 2 | |
| assert refs[0]() is objs[0] | |
| del objs | |
| gc.collect() | |
| keep = [cls() for i in range(100)] | |
| assert [r() for r in refs] == [None] * 100 | |
| assert len(keep) == 100 | |
| def test_weakrefs() -> None: | |
| check(Sub) | |
| check(ExplicitSub) | |
| check(ActionSub) | |
| assert getattr(Sub, "__weakrefoffset__") == getattr(WeakBase, "__weakrefoffset__") | |
| [file other_base.py] | |
| import argparse | |
| from mypy_extensions import mypyc_attr | |
| @mypyc_attr(weakrefs=True) | |
| class WeakBase: | |
| def __init__(self) -> None: | |
| self.x = 1 | |
| class ActionBase(argparse.Action): | |
| def __init__(self) -> None: | |
| super().__init__(["-x"], "x") | |
| self.x = 1 | |
| [case testNonNativeImportInPackageFile] | |
| # The import is really non-native only in separate compilation mode where __init__.py and | |
| # other_cache.py are in different libraries and the import uses the standard Python procedure. | |
| # Python imports are resolved using __path__ and __spec__ from the package file so this checks | |
| # that they are set up correctly. | |
| [file other/__init__.py] | |
| from other.other_cache import Cache | |
| x = 1 | |
| [file other/other_cache.py] | |
| class Cache: | |
| pass | |
| [file driver.py] | |
| import other | |
| [case testRelativeImportInPackageFile] | |
| # Relative imports from a compiled package __init__ depend on package metadata being | |
| # available while the package module body is executing. | |
| [file other/__init__.py] | |
| assert __package__ == "other" | |
| from .other_cache import Cache | |
| x = 1 | |
| [file other/other_cache.py] | |
| class Cache: | |
| pass | |
| [file driver.py] | |
| import other | |
| assert other.Cache.__name__ == "Cache" | |
| [case testMultiModuleSameNames] | |
| # Use same names in both modules | |
| import other | |
| def f() -> int: | |
| return 0 | |
| class C: | |
| x: int | |
| def __init__(self) -> None: | |
| self.x = 1 | |
| def f(self, x: int) -> int: | |
| return self.x + x | |
| class D(C): pass | |
| def g(x: 'other.C') -> None: | |
| pass | |
| [file other.py] | |
| def f(x: int) -> int: | |
| return x + 1 | |
| class C: | |
| x: int | |
| def __init__(self) -> None: | |
| self.x = 2 | |
| def f(self, x: int) -> int: | |
| return self.x + x + 1 | |
| class D(C): pass | |
| [file driver.py] | |
| import native, other | |
| assert native.f() == 0 | |
| assert other.f(3) == 4 | |
| c1 = native.C() | |
| c1.x += 3 | |
| c2 = other.C() | |
| c2.x += 6 | |
| assert c1.f(9) == 1 + 3 + 9 | |
| assert c2.f(7) == 2 + 6 + 7 + 1 | |
| assert isinstance(native.D(), native.C) | |
| assert isinstance(other.D(), other.C) | |
| assert not isinstance(native.D(), other.C) | |
| assert not isinstance(other.D(), native.C) | |
| [case testMultiModuleInitializeImportedModules] | |
| from other import f | |
| def g() -> int: | |
| return f(1) | |
| [file other.py] | |
| def f(x: int) -> int: | |
| return x + 4 | |
| [file driver.py] | |
| import sys | |
| assert 'other' not in sys.modules | |
| from native import g | |
| assert 'other' in sys.modules | |
| assert g() == 5 | |
| f = sys.modules['other'].f | |
| assert f(1) == 5 | |
| try: | |
| f(1.1) | |
| except TypeError: | |
| pass | |
| else: | |
| assert False | |
| [case testMultiModuleImportClass] | |
| from typing import cast | |
| from other import C, a_global | |
| class D(C): | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| def f(c: C) -> int: | |
| d = D(3) | |
| o: object = c | |
| c = cast(C, o) | |
| return a_global + c.x + c.f() + d.x + d.f() + 1 | |
| [file other.py] | |
| from typing import Final | |
| a_global: Final = int('5') | |
| class C: | |
| x: int | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| def __hash__(self) -> int: | |
| return self.x | |
| def __str__(self) -> str: | |
| return str(self.x) | |
| def f(self) -> int: | |
| return 2 | |
| def check(self) -> None: | |
| assert isinstance(self, C) | |
| [file driver.py] | |
| from native import f, D | |
| from other import C | |
| c = C(4) | |
| assert f(c) == 5 + 4 + 2 + 3 + 2 + 1 | |
| assert str(D(10)) == '10' | |
| assert hash(10) == 10 | |
| try: | |
| f(1) | |
| except TypeError: | |
| pass | |
| else: | |
| assert False | |
| assert isinstance(D(10), C) | |
| c.check() | |
| D(10).check() | |
| [case testMultiModuleSpecialize] | |
| from other import A | |
| class B(A): | |
| def foo(self, x: object) -> int: | |
| print(2) | |
| return id(x) | |
| [file other.py] | |
| class A: | |
| def foo(self, x: int) -> object: | |
| print(1) | |
| return str(x) | |
| def use_a(x: A, y: int) -> object: | |
| return x.foo(y) | |
| [file driver.py] | |
| from native import B | |
| from other import A, use_a | |
| a = A() | |
| b = B() | |
| o = object() | |
| i = 10 | |
| assert a.foo(10) == '10' | |
| assert b.foo(o) == id(o) | |
| assert use_a(a, 10) == '10' | |
| assert use_a(b, i) == id(i) | |
| [out] | |
| 1 | |
| 2 | |
| 1 | |
| 2 | |
| [case testMultiModuleLiterals] | |
| from other import gs, gi, gf | |
| def fs() -> str: | |
| return 'f' + gs() | |
| def fi() -> int: | |
| return 10001000100010001000 + gi() | |
| def ff() -> float: | |
| return 2.0 + gf() | |
| [file other.py] | |
| def gi() -> int: | |
| return 20001000100010001000 | |
| def gs() -> str: | |
| return 'g' | |
| def gf() -> float: | |
| return 3.0 | |
| [file driver.py] | |
| from native import fs, fi, ff | |
| assert fs() == 'fg' | |
| assert fi() == 30002000200020002000 | |
| assert ff() == 5.0 | |
| [case testMultiModuleTraceback] | |
| from other import fail2 | |
| def fail() -> None: | |
| fail2() | |
| [file other.py] | |
| def fail2() -> None: | |
| x = [1] | |
| x[2] = 2 | |
| [file driver.py] | |
| import traceback | |
| import sys | |
| import native | |
| import other | |
| try: | |
| other.fail2() | |
| except IndexError: | |
| tb = sys.exc_info()[2] | |
| assert tb.tb_next.tb_frame.f_globals is other.__dict__ | |
| traceback.print_exc() | |
| try: | |
| native.fail() | |
| except IndexError: | |
| tb = sys.exc_info()[2] | |
| assert tb.tb_next.tb_frame.f_globals is native.__dict__ | |
| traceback.print_exc() | |
| [out] | |
| Traceback (most recent call last): | |
| File "driver.py", line 6, in <module> | |
| other.fail2() | |
| File "other.py", line 3, in fail2 | |
| x[2] = 2 | |
| IndexError: list assignment index out of range | |
| Traceback (most recent call last): | |
| File "driver.py", line 12, in <module> | |
| native.fail() | |
| File "native.py", line 4, in fail | |
| fail2() | |
| File "other.py", line 3, in fail2 | |
| x[2] = 2 | |
| IndexError: list assignment index out of range | |
| [out version>=3.13] | |
| Traceback (most recent call last): | |
| File "driver.py", line 6, in <module> | |
| other.fail2() | |
| ~~~~~~~~~~~^^ | |
| File "other.py", line 3, in fail2 | |
| x[2] = 2 | |
| IndexError: list assignment index out of range | |
| Traceback (most recent call last): | |
| File "driver.py", line 12, in <module> | |
| native.fail() | |
| ~~~~~~~~~~~^^ | |
| File "native.py", line 4, in fail | |
| fail2() | |
| File "other.py", line 3, in fail2 | |
| x[2] = 2 | |
| IndexError: list assignment index out of range | |
| [case testMultiModuleCycle] | |
| if False: | |
| from typing import Final | |
| import other | |
| x = int('0') # type: Final | |
| def f1() -> int: | |
| return other.f2() + other.x | |
| def f3() -> int: | |
| return 5 | |
| [file other.py] | |
| if False: | |
| from typing import Final | |
| import native | |
| x = int('0') # type: Final | |
| def f2() -> int: | |
| return native.f3() + native.x | |
| [file driver.py] | |
| from native import f1 | |
| assert f1() == 5 | |
| [case testMultiModuleCycleWithClasses] | |
| import other | |
| class D: pass | |
| def f() -> other.C: | |
| return other.C() | |
| def g(c: other.C) -> D: | |
| return c.d | |
| [file other.py] | |
| import native | |
| class C: | |
| def __init__(self) -> None: | |
| self.d = native.D() | |
| def h(d: native.D) -> None: | |
| pass | |
| [file driver.py] | |
| from native import f, g | |
| from other import C, h | |
| c = f() | |
| assert isinstance(c, C) | |
| assert g(c) is c.d | |
| h(c.d) | |
| try: | |
| g(1) | |
| except TypeError: | |
| pass | |
| else: | |
| assert False | |
| try: | |
| h(1) | |
| except TypeError: | |
| pass | |
| else: | |
| assert False | |
| [case testMultiModuleCycleWithInheritance] | |
| import other | |
| class Deriv1(other.Base1): | |
| def __init__(self) -> None: | |
| super().__init__() | |
| class Base2: | |
| y: int | |
| def __init__(self) -> None: | |
| self.y = 2 | |
| [file other.py] | |
| from typing import Tuple | |
| import native | |
| class Base1: | |
| a: Tuple[int, int] | |
| x: int | |
| def __init__(self) -> None: | |
| self.x = 1 | |
| def make_2() -> native.Base2: | |
| return native.Base2() | |
| [file driver.py] | |
| from native import Deriv1 | |
| from other import make_2 | |
| a = Deriv1() | |
| assert a.x == 1 | |
| b = make_2() | |
| assert b.y == 2 | |
| [case testMultiModuleCycleWithInheritedInit] | |
| # The subclasses are in the module that is processed first. | |
| import other | |
| class Deriv1(other.Base1): | |
| pass | |
| class Deriv2(other.Base2): | |
| pass | |
| [file other.py] | |
| from typing import Any, Callable, TypeVar | |
| import native | |
| F = TypeVar("F", bound=Callable[..., Any]) | |
| def double(f: F) -> F: | |
| def wrapper(self: Any, x: int) -> None: | |
| f(self, x * 2) | |
| return wrapper # type: ignore[return-value] | |
| class Base1: | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| class Base2: | |
| @double | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| def make_1(x: int) -> native.Deriv1: | |
| return native.Deriv1(x) | |
| def make_2(x: int) -> native.Deriv2: | |
| return native.Deriv2(x) | |
| [file driver.py] | |
| from native import Deriv1, Deriv2 | |
| from other import make_1, make_2 | |
| assert Deriv1(1).x == 1 | |
| assert make_1(2).x == 2 | |
| assert Deriv2(3).x == 6 | |
| assert make_2(4).x == 8 | |
| [case testMultiModuleTraitInheritance] | |
| from other import Base1, Base2 | |
| class Deriv1(Base1, Base2): | |
| pass | |
| [file other.py] | |
| from mypy_extensions import trait | |
| @trait | |
| class Base1: | |
| def foo(self) -> int: return 10 | |
| @trait | |
| class Base2: | |
| def bar(self) -> int: return 12 | |
| [file driver.py] | |
| from native import Deriv1 | |
| a = Deriv1() | |
| assert a.foo() == 10 and a.bar() == 12 | |
| [case testImportCycleWithNonCompiledModule] | |
| import m | |
| class C: pass | |
| def f1() -> int: | |
| m.D() | |
| return m.f2() | |
| def f3() -> int: | |
| return 2 | |
| [file m.py] | |
| # This module is NOT compiled | |
| import native | |
| class D: pass | |
| def f2() -> int: | |
| native.C() | |
| return native.f3() | |
| [file driver.py] | |
| from native import f1 | |
| assert f1() == 2 | |
| [case testImportCycleWithTopLevelStatements] | |
| import other | |
| x = 1 | |
| print(x) | |
| [file other.py] | |
| import native | |
| x = 2 | |
| print(x) | |
| [file driver.py] | |
| import other | |
| print('-') | |
| import native | |
| print('>', native.x) | |
| print('>', other.x) | |
| [out] | |
| 1 | |
| 2 | |
| - | |
| > 1 | |
| > 2 | |
| [case testMultiModuleCycleIfMypy1] | |
| from other import foo, bar | |
| class Foo: | |
| def foo(self) -> None: | |
| foo(self) | |
| class Bar: | |
| def bar(self) -> None: | |
| bar(self) | |
| [file other.py] | |
| from typing import TYPE_CHECKING | |
| MYPY = False | |
| if MYPY: | |
| from native import Foo | |
| if TYPE_CHECKING: | |
| from native import Bar | |
| def foo(x: 'Foo') -> None: | |
| pass | |
| def bar(x: 'Bar') -> None: | |
| pass | |
| [file driver.py] | |
| from native import Foo, Bar | |
| Foo().foo() | |
| Bar().bar() | |
| [case testMultiModuleCycleIfMypy2] | |
| MYPY = False | |
| if MYPY: | |
| from other import C | |
| class D: | |
| def __init__(self) -> None: | |
| self.y = 1 | |
| def f(c: 'C') -> int: | |
| return c.x | |
| [file other.py] | |
| from typing import TYPE_CHECKING | |
| if TYPE_CHECKING: | |
| from native import D | |
| class C: | |
| def __init__(self) -> None: | |
| self.x = 2 | |
| def g(d: 'D') -> int: | |
| return d.y | |
| [file driver.py] | |
| from native import f, D | |
| from other import g, C | |
| assert f(C()) == 2 | |
| assert g(D()) == 1 | |
| try: | |
| f(D()) | |
| except TypeError: | |
| pass | |
| else: | |
| assert False | |
| try: | |
| g(C()) | |
| except TypeError: | |
| pass | |
| else: | |
| assert False | |
| [case testMultiModuleAnnotationOfClassNotCreatedYet] | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import TYPE_CHECKING | |
| from mypy_extensions import mypyc_attr | |
| from other_a import A | |
| if TYPE_CHECKING: | |
| from other_b import B | |
| @dataclass(frozen=True) | |
| class Data: | |
| a: A | |
| b: B | |
| quoted: "B" | |
| @mypyc_attr(native_class=False) | |
| class NonNative: | |
| a: A | |
| b: B | |
| [file other_a.py] | |
| class A: | |
| pass | |
| [file other_b.py] | |
| class B: | |
| pass | |
| [file driver.py] | |
| from dataclasses import fields | |
| # Importing native doesn't import other_b, so class B doesn't exist yet when the | |
| # classes in native are created | |
| import native | |
| from other_a import A | |
| assert native.Data.__annotations__ == {"a": A, "b": "other_b.B", "quoted": "other_b.B"} | |
| assert [f.type for f in fields(native.Data)] == [A, "other_b.B", "other_b.B"] | |
| assert native.NonNative.__annotations__ == {"a": A, "b": "other_b.B"} | |
| from other_b import B | |
| d = native.Data(A(), B(), B()) | |
| assert isinstance(d.b, B) | |
| [case testMultiModuleRelative] | |
| from package.a import f | |
| [file package/__init__.py] | |
| [file package/a.py] | |
| from . import b | |
| from .c import c3 | |
| def f() -> None: | |
| print("Hello " + b.b2()) | |
| print("Hello " + c3()) | |
| [file package/b.py] | |
| def b2() -> str: | |
| return "moon!" | |
| [file package/c.py] | |
| def c3() -> str: | |
| return "sun!" | |
| [file driver.py] | |
| from native import f | |
| f() | |
| [out] | |
| Hello moon! | |
| Hello sun! | |
| [case testMultiModuleCrash] | |
| b = False | |
| if b: | |
| import other | |
| def foo() -> None: | |
| try: | |
| other.x | |
| except: | |
| pass | |
| else: | |
| assert False | |
| [file other.py] | |
| x = 10 | |
| [file driver.py] | |
| from native import foo | |
| foo() | |
| [case testTrivialIncremental] | |
| # separate: [(["other.py", "other_b.py"], "stuff")] | |
| from other import x | |
| from other_b import z | |
| y = x + z | |
| [file other.py] | |
| x = 1 | |
| [file other.py.2] | |
| x = 2 | |
| [file other_b.py] | |
| z = 1 | |
| [file driver.py] | |
| from native import y | |
| print(y) | |
| [out] | |
| 2 | |
| [out2] | |
| 3 | |
| [rechecked other, other_b] | |
| [case testIncrementalCompilation1] | |
| import non_native | |
| from other_a import A | |
| from other_b import z | |
| a = A() | |
| assert a.y == z | |
| assert non_native.foo() == 0 | |
| [file other_a.py] | |
| from other_b import z | |
| from typing import Iterable | |
| class A: | |
| def __init__(self) -> None: | |
| self.y = z | |
| [file other_a.py.2] | |
| from other_b import z | |
| from typing import Iterable | |
| class A: | |
| def __init__(self) -> None: | |
| self.x = 'test' | |
| self.y = z | |
| [file other_b.py] | |
| import other_a | |
| z = 10 | |
| def foo() -> 'other_a.A': | |
| return other_a.A() | |
| [file other_b.py.3] | |
| import other_a | |
| z = 20 | |
| def foo() -> 'other_a.A': | |
| return other_a.A() | |
| [file non_native.py] | |
| import other_a | |
| def foo() -> int: | |
| return 0 | |
| [file non_native.py.4] | |
| import other_a | |
| def foo() -> float: | |
| return 0 | |
| [file driver.py] | |
| from native import a | |
| print(a.y, getattr(a, 'x', None)) | |
| [out] | |
| 10 None | |
| [out2] | |
| 10 test | |
| [out3] | |
| 20 test | |
| [out4] | |
| 20 test | |
| [rechecked other_a, other_b, native, non_native] | |
| [rechecked2 other_a, other_b] | |
| [rechecked3 native, non_native] | |
| -- This one tests a group that is not an SCC. | |
| [case testIncrementalCompilation2] | |
| # separate: [(["other_a.py", "other_b.py"], "stuff")] | |
| from other_a import A | |
| from other_b import z | |
| a = A() | |
| assert a.y == z | |
| [file other_a.py] | |
| from other_b import z | |
| class A: | |
| def __init__(self) -> None: | |
| self.y = z | |
| [file other_a.py.2] | |
| from other_b import z | |
| class A: | |
| def __init__(self) -> None: | |
| self.x = 'test' | |
| self.y = z | |
| [file other_b.py] | |
| z = 10 | |
| [file driver.py] | |
| from native import a | |
| print(a.y, getattr(a, 'x', None)) | |
| [out] | |
| 10 None | |
| [out2] | |
| 10 test | |
| [rechecked other_a, other_b, native] | |
| [case testIncrementalCompilation3] | |
| from other import X | |
| Y = X | |
| def foo() -> int: | |
| return X | |
| [file other.py] | |
| from typing import Final | |
| X: Final = 10 | |
| [file other.py.2] | |
| from typing import Final | |
| X: Final = 20 | |
| [file driver.py] | |
| import native | |
| import other | |
| assert native.Y == other.X | |
| assert native.foo() == other.X | |
| [rechecked native, other] | |
| -- This one tests a group changing | |
| [case testIncrementalCompilation4] | |
| # separate: [(["other_a.py", "other_b.py"], "stuff")] | |
| # separate2: [] | |
| from other_a import A | |
| from other_b import z | |
| a = A() | |
| assert a.y == z | |
| [file other_a.py] | |
| from other_b import z | |
| class A: | |
| def __init__(self) -> None: | |
| self.y = z | |
| [file other_b.py] | |
| z = 10 | |
| [file wtvr.py.2] | |
| [file driver.py] | |
| from native import a | |
| print(a.y, getattr(a, 'x', None)) | |
| [out] | |
| 10 None | |
| [out2] | |
| 10 None | |
| [rechecked other_a, other_b, native] | |
| -- This one tests cases where other modules *do not* need rechecked | |
| [case testIncrementalCompilation5] | |
| import other_a | |
| [file other_a.py] | |
| from other_b import f | |
| assert f(10) == 20 | |
| [file other_a.py.2] | |
| from other_b import f | |
| assert f(20) == 40 | |
| [file other_b.py] | |
| def f(x: int) -> int: | |
| return x * 2 | |
| [file driver.py] | |
| import native | |
| [rechecked other_a] | |
| -- Delete one of the C files and make sure this forces recompilation | |
| [case testIncrementalCompilation6] | |
| import other_a | |
| assert other_a.foo() == 10 | |
| [file other_a.py] | |
| def foo() -> int: return 10 | |
| [file build/__native_other_a.c] | |
| [delete build/__native_other_a.c.2] | |
| [file driver.py] | |
| import native | |
| [rechecked other_a] | |
| -- Test that importing a skipped module does not force rechecks. | |
| [case testIncrementalCompilationFollowImportsSkip] | |
| from other_dep import f | |
| assert f() == 1 | |
| [file other_dep.py] | |
| import skipped | |
| def f() -> int: | |
| return 1 | |
| def g() -> int: | |
| return 2 | |
| # Files under "skipped" are not typechecked because of the "--follow_imports = skip" option. | |
| [file skipped/__init__.py] | |
| x = 1 | |
| [file skipped/other_child.py] | |
| import skipped | |
| def child() -> int: | |
| return 1 | |
| [file native.py.2] | |
| from other_dep import g | |
| assert g() == 2 | |
| [file driver.py] | |
| import native | |
| [rechecked native] | |
| [case testSeparateCompilationWithUndefinedAttribute] | |
| from other_a import A | |
| def f() -> None: | |
| a = A() | |
| if a.x == 5: | |
| print(a.y) | |
| print(a.m()) | |
| else: | |
| assert a.x == 6 | |
| try: | |
| print(a.y) | |
| except AttributeError: | |
| print('y undefined') | |
| else: | |
| assert False | |
| try: | |
| print(a.m()) | |
| except AttributeError: | |
| print('y undefined') | |
| else: | |
| assert False | |
| [file other_a.py] | |
| from other_b import B | |
| class A(B): | |
| def __init__(self) -> None: | |
| self.y = 9 | |
| [file other_a.py.2] | |
| from other_b import B | |
| class A(B): | |
| x = 6 | |
| def __init__(self) -> None: | |
| pass | |
| [file other_b.py] | |
| class B: | |
| x = 5 | |
| def __init__(self) -> None: | |
| self.y = 7 | |
| def m(self) -> int: | |
| return self.y | |
| [file driver.py] | |
| from native import f | |
| f() | |
| [rechecked native, other_a] | |
| [out] | |
| 9 | |
| 9 | |
| [out2] | |
| y undefined | |
| y undefined | |
| [case testIncrementalCompilationWithDeletable] | |
| import other_a | |
| [file other_a.py] | |
| from other_b import C | |
| [file other_a.py.2] | |
| from other_b import C | |
| c = C() | |
| print(getattr(c, 'x', None)) | |
| del c.x | |
| print(getattr(c, 'x', None)) | |
| [file other_b.py] | |
| class C: | |
| __deletable__ = ['x'] | |
| def __init__(self) -> None: | |
| self.x = 0 | |
| [file driver.py] | |
| import native | |
| [out] | |
| [out2] | |
| 0 | |
| None | |
| [case testIncrementalCompilationWithNonExtClass] | |
| import other_a | |
| [file other_a.py] | |
| from other_b import C | |
| [file other_a.py.2] | |
| from other_b import C | |
| c = C(5) | |
| print(c.x) | |
| [file other_b.py] | |
| from mypy_extensions import mypyc_attr | |
| @mypyc_attr(native_class=False) | |
| class C: | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| [file driver.py] | |
| import native | |
| [out] | |
| [out2] | |
| 5 | |
| [case testIncrementalCompilationAddingNonClassDecorator] | |
| # Mypy ignores class decorators, but adding one that replaces the class must | |
| # recompile native.py, since C then no longer refers to the class itself. | |
| from typing import Any, cast | |
| from other import C | |
| def same_instance() -> bool: | |
| cls = cast(Any, C) | |
| return cls() is cls() | |
| [file other.py] | |
| from functools import cache | |
| from mypy_extensions import mypyc_attr | |
| @mypyc_attr(native_class=False) | |
| class C: | |
| pass | |
| [file other.py.2] | |
| from functools import cache | |
| from mypy_extensions import mypyc_attr | |
| @cache | |
| @mypyc_attr(native_class=False) | |
| class C: | |
| pass | |
| [file other.py.3] | |
| from functools import cache | |
| from mypy_extensions import mypyc_attr | |
| @mypyc_attr(native_class=False) | |
| class C: | |
| pass | |
| [file driver.py] | |
| from native import same_instance | |
| from other import C | |
| print(same_instance(), C() is C()) | |
| [out] | |
| False False | |
| [out2] | |
| True True | |
| [out3] | |
| False False | |
| [rechecked native, other] | |
| [rechecked2 native, other] | |
| [case testIncrementalCompilationAddingNonClassDecoratorToNativeClass] | |
| # The decorator also makes C a non-native class, which changes how native.py | |
| # constructs it. In step 3 other.py is unchanged, so it must stay fresh. | |
| from other import C | |
| def get() -> int: | |
| return C(3).get() | |
| def same_instance() -> bool: | |
| return C(1) is C(1) | |
| [file native.py.3] | |
| from other import C | |
| def get() -> int: | |
| return C(4).get() | |
| def same_instance() -> bool: | |
| return C(1) is C(1) | |
| [file other.py] | |
| from functools import cache | |
| class C: | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| def get(self) -> int: | |
| return self.x | |
| [file other.py.2] | |
| from functools import cache | |
| @cache | |
| class C: | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| def get(self) -> int: | |
| return self.x | |
| [file driver.py] | |
| from native import get, same_instance | |
| print(get(), same_instance()) | |
| [out] | |
| 3 False | |
| [out2] | |
| 3 True | |
| [out3] | |
| 4 True | |
| [rechecked native, other] | |
| [rechecked2 native] | |
| [case testIncrementalCompilationWithNonClassTypeDef] | |
| import other_a | |
| [file other_a.py] | |
| from other_b import MyInt | |
| [file other_a.py.2] | |
| from other_b import MyInt, NT, TD | |
| i = MyInt(42) | |
| def f(x: MyInt) -> int: | |
| return x + 1 | |
| def g(x: int) -> MyInt: | |
| return MyInt(x + 2) | |
| print(i) | |
| print(f(i)) | |
| print(g(13)) | |
| def make_nt(x: int) -> NT: | |
| return NT(x=MyInt(x)) | |
| print(make_nt(4)) | |
| def make_td(x: int) -> TD: | |
| return {"x": MyInt(x)} | |
| print(make_td(5)) | |
| [file other_b.py] | |
| from typing import NewType, NamedTuple, TypedDict | |
| from enum import Enum | |
| MyInt = NewType("MyInt", int) | |
| NT = NamedTuple("NT", [("x", MyInt)]) | |
| TD = TypedDict("TD", {"x": MyInt}) | |
| [file driver.py] | |
| import native | |
| [typing fixtures/typing-full.pyi] | |
| [out] | |
| [out2] | |
| 42 | |
| 43 | |
| 15 | |
| NT(x=4) | |
| {'x': 5} | |
| [case testIncrementalCompilationTogglingNonExtClass] | |
| # Mypy ignores mypyc_attr, so making C a non-native class (or a native class | |
| # again) doesn't change the interface of other.py. native.py must still be | |
| # recompiled, since it constructs C and accesses its attributes differently. | |
| # In step 3 other.py is unchanged, so it must stay fresh. | |
| from other import C | |
| def make(x: int) -> C: | |
| return C(x) | |
| def get(c: C) -> int: | |
| return c.x | |
| [file other.py] | |
| from mypy_extensions import mypyc_attr | |
| class C: | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| [file other.py.2] | |
| from mypy_extensions import mypyc_attr | |
| @mypyc_attr(native_class=False) | |
| class C: | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| [file native.py.3] | |
| from other import C | |
| def make(x: int) -> C: | |
| return C(x + 1) | |
| def get(c: C) -> int: | |
| return c.x | |
| [file other.py.4] | |
| from mypy_extensions import mypyc_attr | |
| class C: | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| [file driver.py] | |
| from native import get, make | |
| c = make(3) | |
| print(get(c), hasattr(c, "__dict__")) | |
| [out] | |
| 3 False | |
| [out2] | |
| 3 True | |
| [out3] | |
| 4 True | |
| [out4] | |
| 4 False | |
| [rechecked native, other] | |
| [rechecked2 native] | |
| [rechecked3 native, other] | |
| [case testIncrementalCompilationTogglingTrait] | |
| # Mypy also ignores @trait. Making T a trait changes how other.py calls m(), | |
| # so native.py must be recompiled to give D a vtable that matches. | |
| # In step 3 other.py is unchanged, so it must stay fresh. | |
| from other import T | |
| class D(T): | |
| def m(self) -> int: | |
| return 2 | |
| [file other.py] | |
| from mypy_extensions import trait | |
| class T: | |
| def m(self) -> int: | |
| return 1 | |
| def call(t: T) -> int: | |
| return t.m() | |
| [file other.py.2] | |
| from mypy_extensions import trait | |
| @trait | |
| class T: | |
| def m(self) -> int: | |
| return 1 | |
| def call(t: T) -> int: | |
| return t.m() | |
| [file native.py.3] | |
| from other import T | |
| class D(T): | |
| def m(self) -> int: | |
| return 3 | |
| [file other.py.4] | |
| from mypy_extensions import trait | |
| class T: | |
| def m(self) -> int: | |
| return 1 | |
| def call(t: T) -> int: | |
| return t.m() | |
| [file driver.py] | |
| from native import D | |
| from other import call | |
| print(call(D())) | |
| [out] | |
| 2 | |
| [out2] | |
| 2 | |
| [out3] | |
| 3 | |
| [out4] | |
| 3 | |
| [rechecked native, other] | |
| [rechecked2 native] | |
| [rechecked3 native, other] | |
| [case testExtraLibRtSourceFileDep] | |
| table_list = list(range(256)) | |
| table_list[ord('A')] = ord('B') | |
| table = bytes(table_list) | |
| def translate(b: bytes) -> bytes: | |
| # The primimitive for bytes.translate requires an optional C file from lib-rt | |
| return b.translate(table) | |
| [file driver.py] | |
| import native | |
| assert native.translate(b'ABCD') == b'BBCD' | |
| [case testIncrementalCrossGroupExportTableOffsets] | |
| # Regression: under separate=True, each consumer module's IR is | |
| # compiled against the positional layout of its deps' | |
| # `exports_<group>` struct. Reordering the dep's classes keeps the | |
| # same set of public names, so mypy's interface hash for the dep is | |
| # unchanged -- the consumer is not invalidated and stays fully | |
| # cached, which causes `_load_cached_group_files` to return empty | |
| # cfile content for the consumer's group. | |
| # | |
| # Before the fix, `get_header_deps` over empty content returned no | |
| # includes, so `Extension.depends` for the consumer ended up empty | |
| # and setuptools never recompiled the consumer's .o when the dep's | |
| # `__native_<dep>.h` shifted struct offsets. The stale .o kept the | |
| # old offsets and silently resolved cross-group calls to the wrong | |
| # class. | |
| from other_classes import Gamma, Delta | |
| def make_gamma() -> Gamma: | |
| return Gamma() | |
| def make_delta() -> Delta: | |
| return Delta() | |
| [file other_classes.py] | |
| class Alpha: | |
| a: int = 1 | |
| class Beta: | |
| b: int = 2 | |
| class Gamma: | |
| g: int = 3 | |
| class Delta: | |
| d: int = 4 | |
| [file other_classes.py.2] | |
| class Delta: | |
| d: int = 4 | |
| class Alpha: | |
| a: int = 1 | |
| class Beta: | |
| b: int = 2 | |
| class Gamma: | |
| g: int = 3 | |
| [file driver.py] | |
| import native | |
| assert type(native.make_gamma()).__name__ == "Gamma" | |
| assert type(native.make_delta()).__name__ == "Delta" | |
| [case testCrossModuleAttrDefaults] | |
| from other import Parent | |
| class Child(Parent): | |
| extra: int = 99 | |
| def test() -> None: | |
| c = Child() | |
| assert c.config == {"key": "value"} | |
| assert c.extra == 99 | |
| assert c.total == 60 | |
| p = Parent() | |
| assert p.config == {"key": "value"} | |
| assert p.total == 60 | |
| assert Parent.TAG == "parent" | |
| [file other.py] | |
| from typing import ClassVar, Dict | |
| MY_DEFAULT: Dict[str, str] = {"key": "value"} | |
| VAL_1: int = 10 | |
| VAL_2: int = 20 | |
| VAL_3: int = 30 | |
| class Parent: | |
| config: Dict[str, str] = MY_DEFAULT | |
| total: int = VAL_1 + VAL_2 + VAL_3 | |
| TAG: ClassVar[str] = "parent" | |
| [file driver.py] | |
| from native import test | |
| test() | |
| [case testIncrementalCrossModuleInheritedAttrDefaults] | |
| # Regression: under separate=True, when only the subclass module is | |
| # recompiled (parent loaded from mypy's incremental cache, so its | |
| # ClassDef.defs.body is empty), the subclass produces no | |
| # __mypyc_defaults_setup of its own and ClassIR.get_method returns | |
| # the parent's. The emitted call must use the cross-group | |
| # exports_<group>. prefix, otherwise the generated C references an | |
| # undeclared symbol and clang/gcc fail to compile. | |
| import other_a | |
| def test() -> None: | |
| c = other_a.Child() | |
| assert c.x == 1 | |
| assert c.y == "hello" | |
| [file other_b.py] | |
| class Parent: | |
| x: int = 1 | |
| y: str = "hello" | |
| [file other_a.py] | |
| from other_b import Parent | |
| class Child(Parent): | |
| pass | |
| [file other_a.py.2] | |
| from other_b import Parent | |
| class Child(Parent): | |
| pass | |
| def _force_recompile() -> int: | |
| return 1 | |
| [file driver.py] | |
| from native import test | |
| test() | |
| [case testExtraOpsFunction_experimental_librt] | |
| from librt.strings import BytesWriter | |
| def call_write(b: bytes) -> bytes: | |
| w = BytesWriter() | |
| w.write(b) # calls CPyBytesWriter_Write defined in byteswriter_extra_ops.c | |
| return w.getvalue() | |
| [file other.py] | |
| from native import call_write | |
| def test(b: bytes) -> bytes: | |
| return call_write(b) | |
| [file driver.py] | |
| from other import test | |
| input = b'x' * 512 | |
| assert test(input) == input | |
| [case testLibrtDependencyInImportedFile_experimental_librt] | |
| # Test that a compiled file (other.py) that does not depend on librt can import another compiled | |
| # file (native.py) that does. | |
| from librt.vecs import vec, append, pop | |
| def call_append(s: str) -> str: | |
| v = vec[str]() | |
| v = append(v, s) | |
| _, rv = pop(v) | |
| return rv | |
| [file other.py] | |
| from native import call_append | |
| def test_append() -> None: | |
| assert call_append("test123") == "test123" | |
| [file driver.py] | |
| from other import test_append | |
| test_append() | |
| [case testIndirectLibrtDependency_experimental_librt] | |
| # Test that a compiled file (other.py) that indirectly depends on librt can import another compiled | |
| # file (native.py) that directly depends on it. | |
| from librt.strings import BytesWriter, write_i16_le | |
| from librt.vecs import vec, append, pop | |
| from mypy_extensions import i64 | |
| glob_bw = BytesWriter() | |
| glob_vec = vec[str](["one", "two", "three"]) | |
| def fn_returns_bw(b: bytes) -> BytesWriter: | |
| w = BytesWriter() | |
| w.write(b) | |
| return w | |
| def fn_returns_vec(i: i64) -> vec[i64]: | |
| v = vec[i64]() | |
| v = append(v, i) | |
| return v | |
| class ClassWithLibrtTypeMember: | |
| def __init__(self, w: BytesWriter, v: vec[str]) -> None: | |
| self.writer = w | |
| self.vec = vec[vec[str]]([v]) | |
| def method_returns_bw(self) -> BytesWriter: | |
| return self.writer | |
| def method_returns_vec(self) -> vec[vec[str]]: | |
| return self.vec | |
| [file other.py] | |
| import struct | |
| from native import ( | |
| glob_bw, glob_vec, fn_returns_bw, fn_returns_vec, ClassWithLibrtTypeMember, write_i16_le, pop | |
| ) | |
| from mypy_extensions import i64 | |
| def test_global(b: bytes) -> None: | |
| glob_bw.write(b) | |
| assert glob_bw.getvalue() == b | |
| glob_vec[1] = "not two" | |
| assert glob_vec[1] == "not two" | |
| def test_fn(b: bytes, i: i64) -> None: | |
| assert fn_returns_bw(b).getvalue() == b | |
| assert fn_returns_vec(i)[0] == i | |
| def test_class(b: bytes) -> None: | |
| c = ClassWithLibrtTypeMember(glob_bw, glob_vec) | |
| assert c.method_returns_bw().getvalue() == b | |
| assert c.method_returns_vec()[0] == glob_vec | |
| def test_reexport() -> None: | |
| write_i16_le(glob_bw, 42) | |
| assert glob_bw.getvalue()[-2:] == struct.pack("<h", 42) | |
| glob_vec, s = pop(glob_vec) | |
| assert len(glob_vec) == 2 | |
| assert s == "three" | |
| [file driver.py] | |
| from other import test_global, test_fn, test_class, test_reexport | |
| input = b'x' * 512 | |
| test_global(input) | |
| test_fn(input, 512) | |
| test_class(input) | |
| test_reexport() | |
| [case testLibrtInternalInImportedFile_librt_internal] | |
| from librt.internal import ReadBuffer, WriteBuffer, write_str, read_str, cache_version | |
| def get_buffer_round_trip_result(s: str) -> str: | |
| assert cache_version() == 0 | |
| w = WriteBuffer() | |
| write_str(w, s) | |
| r = ReadBuffer(w.getvalue()) | |
| return read_str(r) | |
| [file other.py] | |
| from native import get_buffer_round_trip_result | |
| def test_buffer_round_trip() -> None: | |
| assert get_buffer_round_trip_result("foo") == "foo" | |
| [file driver.py] | |
| from other import test_buffer_round_trip | |
| test_buffer_round_trip() | |
| -- Regression tests for separate=True compilation. | |
| [case testSeparateCrossGroupEnumMethod] | |
| -- Under separate=True, methods of non-extension classes (like Enum subclasses) | |
| -- are compiled as direct C functions rather than vtable entries. | |
| -- `is_method_final` must short-circuit to True for non-ext classes so the | |
| -- cross-group call site emits a direct call rather than indexing into a | |
| -- vtable that `compute_vtable` skipped. | |
| from other_enum import Color | |
| def name_of_red() -> str: | |
| return Color.RED.describe() | |
| def name_of_blue() -> str: | |
| return Color.BLUE.describe() | |
| [file other_enum.py] | |
| from enum import Enum | |
| class Color(Enum): | |
| RED = 1 | |
| BLUE = 2 | |
| def describe(self) -> str: | |
| return "color:" + self.name | |
| [file driver.py] | |
| from native import name_of_red, name_of_blue | |
| assert name_of_red() == "color:RED" | |
| assert name_of_blue() == "color:BLUE" | |
| [case testSeparateCrossGroupGenerator] | |
| -- Under separate=True, mypyc-generated generator helper classes have their | |
| -- FuncIR bodies in the defining group; consumers only see FuncDecl via | |
| -- `method_decls`. `emit_method_call` must use `method_decl(name)` rather | |
| -- than asserting `get_method(name).decl` is non-None. | |
| from other_gen import count_up | |
| def sum_range(n: int) -> int: | |
| total = 0 | |
| for x in count_up(n): | |
| total += x | |
| return total | |
| [file other_gen.py] | |
| from typing import Iterator | |
| def count_up(n: int) -> Iterator[int]: | |
| i = 0 | |
| while i < n: | |
| yield i | |
| i += 1 | |
| [file driver.py] | |
| from native import sum_range | |
| assert sum_range(0) == 0 | |
| assert sum_range(1) == 0 | |
| assert sum_range(5) == 10 | |
| [case testPackageCycleInheritedEq] | |
| -- Regression test for generating __ne__ from an inherited __eq__ when the | |
| -- inherited method's declaration is available before its FuncIR body has been | |
| -- generated. This can happen in package import cycles where __init__ imports a | |
| -- child module before the subpackage that defines the base class. | |
| from other.other_child import Child | |
| def make_child() -> Child: | |
| return Child() | |
| [file other/__init__.py] | |
| from other.other_child import Child as Child | |
| from other.other_subpkg import Base as Base | |
| [file other/other_child.py] | |
| from other.other_subpkg import Base | |
| class Child(Base): | |
| pass | |
| [file other/other_subpkg/__init__.py] | |
| from other.other_subpkg.other_base import Base as Base | |
| [file other/other_subpkg/other_base.py] | |
| class Base: | |
| def __eq__(self, other: object) -> bool: | |
| return True | |
| [file driver.py] | |
| from native import make_child | |
| left = make_child() | |
| right = make_child() | |
| assert left == right | |
| assert not (left != right) | |
| [case testSeparateCrossGroupInheritedInit] | |
| -- Under separate=True, a subclass whose __init__ is inherited from a | |
| -- different group must call the base's CPyPy_ wrapper through the exports | |
| -- table. This exercises `wrapper_function_call` in `generate_init_for_class` | |
| -- / `emit_setup_or_dunder_new_call`, and requires the CPyPy_ wrapper decl | |
| -- to be marked `needs_export=True` so it reaches the exports table. | |
| from other_base import Base | |
| class Child(Base): | |
| def label(self) -> str: | |
| return "child(" + str(self.x) + ")" | |
| def make_child(n: int) -> str: | |
| return Child(n).label() | |
| [file other_base.py] | |
| class Base: | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| [file driver.py] | |
| from native import make_child | |
| assert make_child(7) == "child(7)" | |
| assert make_child(-1) == "child(-1)" | |
| [case testIncrementalCrossGroupDecoratedInit] | |
| # A class with a decorated __init__ is initialized through tp_init, and so is | |
| # a subclass that inherits the __init__. When only the module of the subclass | |
| # is recompiled, the base class is loaded from the incremental cache, which | |
| # doesn't have the decorators. | |
| from other_a import Child, ChildWithInit | |
| from other_b import Base, log | |
| def take() -> list[str]: | |
| result = list(log) | |
| log.clear() | |
| return result | |
| def test() -> None: | |
| log.clear() | |
| b = Base(1) | |
| assert take() == ["before (1,)", "Root 1", "Base 1", "after"] | |
| assert b.x == 1 | |
| c = Child(2) | |
| assert take() == ["before (2,)", "Root 2", "Base 2", "after"] | |
| assert c.x == 2 | |
| d = ChildWithInit() | |
| assert take() == ["before (3,)", "Root 3", "Base 3", "after", "ChildWithInit"] | |
| assert d.x == 3 | |
| [file other_a.py] | |
| from other_b import Base, log | |
| class Child(Base): | |
| pass | |
| class ChildWithInit(Base): | |
| def __init__(self) -> None: | |
| super().__init__(3) | |
| log.append("ChildWithInit") | |
| [file other_a.py.2] | |
| from other_b import Base, log | |
| class Child(Base): | |
| pass | |
| class ChildWithInit(Base): | |
| def __init__(self) -> None: | |
| super().__init__(3) | |
| log.append("ChildWithInit") | |
| def _force_recompile() -> int: | |
| return 1 | |
| [file other_b.py] | |
| from typing import Any, Callable, TypeVar | |
| F = TypeVar("F", bound=Callable[..., Any]) | |
| log: list[str] = [] | |
| def logged(f: F) -> F: | |
| def wrapper(self: Any, *args: Any) -> None: | |
| log.append(f"before {args}") | |
| f(self, *args) | |
| log.append("after") | |
| return wrapper # type: ignore[return-value] | |
| class Root: | |
| def __init__(self, x: int) -> None: | |
| log.append(f"Root {x}") | |
| self.x = x | |
| class Base(Root): | |
| @logged | |
| def __init__(self, x: int) -> None: | |
| super().__init__(x) | |
| log.append(f"Base {x}") | |
| [file driver.py] | |
| from native import test | |
| test() | |
| [case testIncrementalBuiltinBaseClassConstruction] | |
| # Regression: builtin_base classes (Exception subclasses) were unconditionally | |
| # added to func_to_decl in load_type_map, causing cross-group call sites to | |
| # emit CPyDef instead of CPyType for the constructor. | |
| from other_errors import MyError | |
| from other_util import process | |
| def run(value: str) -> None: | |
| if not value: | |
| raise MyError("empty") | |
| def compute(x: str) -> str: | |
| result = process(x) | |
| if not result: | |
| raise MyError("no result") | |
| return result | |
| [file other_errors.py] | |
| class MyError(Exception): | |
| pass | |
| [file other_util.py] | |
| def process(x: str) -> str: | |
| return x | |
| [file other_util.py.2] | |
| def process(x: str, flag: bool = False) -> str: | |
| return x.strip() | |
| [file driver.py] | |
| from native import run, compute | |
| try: | |
| run("") | |
| except Exception as e: | |
| print(str(e)) | |
| print(compute("hello")) | |
| [out] | |
| empty | |
| hello | |
| [out2] | |
| empty | |
| hello | |
| [case testIncrementalCrossGroupDecoratedDunderNew] | |
| # A class with a decorated __new__ inherits tp_new, and so does a subclass that | |
| # inherits the __new__. When only the module of the subclass is recompiled, the | |
| # base class is loaded from the incremental cache, which doesn't have the | |
| # decorators. | |
| from typing import Any | |
| from other_a import Child, ChildWithInit | |
| from other_b import Base, log | |
| def take() -> list[str]: | |
| result = list(log) | |
| log.clear() | |
| return result | |
| def test() -> None: | |
| log.clear() | |
| any_base: Any = Base | |
| for base in Base, any_base: | |
| b = base(1) | |
| assert take() == ["before Base (1,)", "new", "after", "Root 1"] | |
| assert b.x == 1 | |
| # Use Any to get non-native semantics | |
| any_child: Any = Child | |
| for child in Child, any_child: | |
| c = child(2) | |
| assert take() == ["before Child (2,)", "new", "after", "Root 2"] | |
| assert type(c) is Child | |
| assert c.x == 2 | |
| any_child = ChildWithInit | |
| for child_with_init in ChildWithInit, any_child: | |
| d = child_with_init(3) | |
| assert take() == ["before ChildWithInit (3,)", "new", "after", "Root 4", "ChildWithInit"] | |
| assert d.x == 4 | |
| e = Base.__new__(Child, 4) | |
| assert take() == ["before Child (4,)", "new", "after"] | |
| assert type(e) is Child | |
| [file other_a.py] | |
| from other_b import Base, log | |
| class Child(Base): | |
| pass | |
| class ChildWithInit(Base): | |
| def __init__(self, x: int) -> None: | |
| super().__init__(x + 1) | |
| log.append("ChildWithInit") | |
| [file other_a.py.2] | |
| from other_b import Base, log | |
| class Child(Base): | |
| pass | |
| class ChildWithInit(Base): | |
| def __init__(self, x: int) -> None: | |
| super().__init__(x + 1) | |
| log.append("ChildWithInit") | |
| def _force_recompile() -> int: | |
| return 1 | |
| [file other_b.py] | |
| from typing import Any, Callable, TypeVar | |
| F = TypeVar("F", bound=Callable[..., Any]) | |
| log: list[str] = [] | |
| def logged(f: F) -> F: | |
| def wrapper(cls: Any, *args: Any) -> Any: | |
| log.append(f"before {cls.__name__} {args}") | |
| obj = f(cls, *args) | |
| log.append("after") | |
| return obj | |
| return wrapper # type: ignore[return-value] | |
| class Root: | |
| def __init__(self, x: int) -> None: | |
| log.append(f"Root {x}") | |
| self.x = x | |
| class Base(Root): | |
| @logged | |
| def __new__(cls, x: int) -> Any: | |
| log.append("new") | |
| return super().__new__(cls) | |
| [file driver.py] | |
| from native import test | |
| test() | |
| [case testDecoratedNewInBaseClassPreparedAfterSubclass] | |
| # The modules of a compilation group are prepared in name order, so Child is | |
| # prepared before Base. mypy removes @staticmethod from the decorators of | |
| # __new__, so it's a native method, and the constructor of Child calls it and | |
| # __init__ natively. | |
| from other import Base | |
| class Child(Base): | |
| def __init__(self) -> None: | |
| raise ValueError("expected init failure") | |
| def construct() -> Child: | |
| return Child() | |
| [file other.py] | |
| from typing import Any | |
| class Base: | |
| @staticmethod | |
| def __new__(cls) -> Any: | |
| return super().__new__(cls) | |
| def __init__(self) -> None: | |
| pass | |
| [file driver.py] | |
| from native import construct | |
| from testutil import assertRaises | |
| with assertRaises(ValueError): | |
| construct() | |
| [case testIncrementalCrossModuleInheritedAttrDefaultsWithOverride] | |
| # Regression: same shape as testIncrementalCrossModuleInheritedAttrDefaults, | |
| # but the subclass adds an attribute of its own, so generate_attr_defaults_init | |
| # emits a __mypyc_defaults_setup for it. Before the fix, the recompiled | |
| # subclass walked the parent's ClassDef.defs.body to collect inherited | |
| # defaults; when the parent was loaded from mypy's incremental cache that | |
| # body was empty, so the inherited initialization was dropped and any | |
| # access to an inherited attribute through compiled code raised | |
| # "AttributeError: attribute '<name>' of '<base>' undefined". | |
| import other_a | |
| def test() -> None: | |
| c = other_a.Child() | |
| # Inherited attributes must still be initialized after the subclass | |
| # has been recompiled against a cache-loaded parent. | |
| assert c.x == 1 | |
| assert c.y == "hello" | |
| # Own override is set by the subclass's own __mypyc_defaults_setup. | |
| assert c.z is True | |
| # Method defined on the parent reads an inherited attribute through | |
| # the compiled path; this is what crashes pre-fix. | |
| assert c.use() == 1 | |
| [file other_b.py] | |
| class Parent: | |
| x: int = 1 | |
| y: str = "hello" | |
| z: bool = False | |
| def use(self) -> int: | |
| if self.x: | |
| return 1 | |
| return 0 | |
| [file other_a.py] | |
| from other_b import Parent | |
| class Child(Parent): | |
| z: bool = True | |
| [file other_a.py.2] | |
| from other_b import Parent | |
| class Child(Parent): | |
| z: bool = True | |
| def _force_recompile() -> int: | |
| return 1 | |
| [file driver.py] | |
| from native import test | |
| test() | |
| [case testIncrementalCrossGroupInheritedMethodRemoved] | |
| # Regression: updating a transitive base class triggers recompilation of the | |
| # subclass-defining module (mypy#21742). | |
| import other_leaf | |
| def test() -> int: | |
| c = other_leaf.Leaf() | |
| return c.existing_method(5) | |
| [file other_base.py] | |
| class Base: | |
| def existing_method(self, x: int) -> int: | |
| return x + 1 | |
| def removed_method(self, x: int) -> int: | |
| return x + 100 | |
| [file other_base.py.2] | |
| class Base: | |
| def existing_method(self, x: int) -> int: | |
| return x + 1 | |
| [file other_mid.py] | |
| from other_base import Base | |
| class Mid(Base): | |
| def mid_method(self, x: int) -> int: | |
| return x + 2 | |
| [file other_leaf.py] | |
| from other_mid import Mid | |
| class Leaf(Mid): | |
| pass | |
| [file driver.py] | |
| from native import test | |
| print(test()) | |
| [out] | |
| 6 | |
| [out2] | |
| 6 | |
| [case testIncrementalCrossGroupInheritedMethodRemovedNonEmptyLeaf] | |
| # Regression: updating a transitive base class triggers recompilation of the | |
| # module defining a subclass with a non-empty body (mypy#21742). | |
| import other_leaf | |
| def test() -> int: | |
| return other_leaf.Leaf().existing_method(5) | |
| [file other_base.py] | |
| class Base: | |
| def existing_method(self, x: int) -> int: | |
| return x + 1 | |
| def removed_method(self, x: int) -> int: | |
| return x + 100 | |
| [file other_base.py.2] | |
| class Base: | |
| def existing_method(self, x: int) -> int: | |
| return x + 1 | |
| [file other_mid.py] | |
| from other_base import Base | |
| class Mid(Base): | |
| def mid_method(self, x: int) -> int: | |
| return x + 2 | |
| [file other_leaf.py] | |
| from other_mid import Mid | |
| class Leaf(Mid): | |
| FLAG = True | |
| def foo(self) -> str: | |
| return "foo" | |
| [file driver.py] | |
| from native import test | |
| print(test()) | |
| [out] | |
| 6 | |
| [out2] | |
| 6 | |
| [case testCrossModuleInheritedAttrDefaultsSameGroup] | |
| # separate: [(["native.py"], "grp1"), (["other_a.py", "other_b.py"], "grp2")] | |
| # Regression: with the subclass (other_a) and base (other_b) in the same | |
| # compilation group, IR build runs alphabetically within the group, so | |
| # the subclass is IR-built before the base. The decision to emit | |
| # __mypyc_defaults_setup (and a chained call to the ancestor's) must be | |
| # set up in the prepare phase, before any IR build runs; otherwise the | |
| # subclass's lookup of the parent's setup decl misses and inherited | |
| # defaults are lost on a fresh build. | |
| import other_a | |
| def test() -> None: | |
| c = other_a.Child() | |
| assert c.x == 1 | |
| assert c.z is True | |
| [file other_b.py] | |
| class Parent: | |
| x: int = 1 | |
| [file other_a.py] | |
| from other_b import Parent | |
| class Child(Parent): | |
| z: bool = True | |
| [file driver.py] | |
| from native import test | |
| test() | |
| [case testCompiledSubclassOfCompiledBaseThatAllowsInterpretedSubclasses] | |
| from mypy_extensions import mypyc_attr | |
| from other import CompiledBase | |
| class CompiledSubclass(CompiledBase): | |
| def value(self) -> int: | |
| return 1 | |
| @mypyc_attr(allow_interpreted_subclasses=True) | |
| class CompiledSubclassThatAllowsInterpreted(CompiledBase): | |
| def value(self) -> int: | |
| return 2 | |
| def test_compiled_subclasses_of_compiled_base_that_allows_interpreted_subclasses() -> None: | |
| c1 = CompiledSubclass() | |
| assert c1.value() == 1 | |
| c2 = CompiledSubclassThatAllowsInterpreted() | |
| assert c2.value() == 2 | |
| [file other.py] | |
| from mypy_extensions import mypyc_attr | |
| @mypyc_attr(allow_interpreted_subclasses=True) | |
| class CompiledBase: | |
| def value(self) -> int: | |
| raise NotImplementedError | |
| [case testMultiModuleCallTypeObjectWithInheritedInit] | |
| from other import Base | |
| class Child(Base): | |
| pass | |
| [file other.py] | |
| class Base: | |
| def __init__(self, x: int) -> None: | |
| self.x = x | |
| [file driver.py] | |
| import other | |
| from native import Child | |
| c = Child(7) | |
| assert type(c) is Child | |
| assert c.x == 7 | |
| assert Child(x=8).x == 8 | |
| # An argument with the wrong type is reported in __init__, which is in another module. | |
| try: | |
| Child("7") | |
| except TypeError as e: | |
| assert str(e) == "int object expected; got str" | |
| tb = e.__traceback__.tb_next | |
| assert tb.tb_frame.f_globals is other.__dict__ | |
| assert tb.tb_frame.f_code.co_name == "__init__" | |
| assert tb.tb_lineno == 2 | |
| else: | |
| assert False | |
| [case testSeparateCrossGroupUnpackedArgs] | |
| -- A call with *args or **kwargs that a native call can't unpack goes through the | |
| -- wrapper function of the method. Under separate=True, the wrapper of a method in | |
| -- another group is called through the exports table. | |
| from typing import Any | |
| from other_base import Base | |
| class Child(Base): | |
| def __init__(self, *args: Any, **kwargs: Any) -> None: | |
| super().__init__(*args, **kwargs) | |
| def add(self, *args: int, **kwargs: int) -> int: | |
| return super().add(*args, **kwargs) + 100 | |
| def make(*args: Any, **kwargs: Any) -> tuple[int, int, int]: | |
| c = Child(*args, **kwargs) | |
| return c.x, c.y, c.add(c.x, y=c.y) | |
| [file other_base.py] | |
| class Base: | |
| def __init__(self, x: int, y: int = 0) -> None: | |
| self.x = x | |
| self.y = y | |
| def add(self, x: int, y: int = 0) -> int: | |
| return x + y | |
| [file driver.py] | |
| from native import make | |
| assert make(1) == (1, 0, 101), make(1) | |
| assert make(1, y=2) == (1, 2, 103), make(1, y=2) | |
| assert make(x=3, y=4) == (3, 4, 107), make(x=3, y=4) | |
| [case testFinalMethodCallsWithinAndAcrossModules] | |
| from other import FinalMethods, NativeBaseWithFinals, FinalTrait, SubclassOfNativeBase, SubclassOfTrait | |
| def cross_module_calls(obj: FinalMethods) -> tuple[int, int, int, int, int, int, int]: | |
| return ( | |
| obj.regular(2), | |
| obj.class_method(2), | |
| obj.static_method(2), | |
| sum(obj.generator(2)), | |
| FinalMethods.class_method(3), | |
| FinalMethods.static_method(3), | |
| obj.decorated_final(2), | |
| ) | |
| async def cross_module_async(obj: FinalMethods) -> tuple[int, int, int, int, int]: | |
| return ( | |
| await obj.async_method(2), | |
| await obj.async_class_method(2), | |
| await obj.async_static_method(2), | |
| await FinalMethods.async_class_method(3), | |
| await FinalMethods.async_static_method(3), | |
| ) | |
| def cross_module_property_calls(obj: FinalMethods) -> tuple[int, int]: | |
| return (obj.final_prop, obj.computed_prop) | |
| def cross_module_native_base_calls(obj: NativeBaseWithFinals) -> tuple[int, int, int]: | |
| return (obj.base_method(5), obj.base_prop, obj.computed_base_prop) | |
| def cross_module_trait_calls(obj: FinalTrait) -> tuple[int, int]: | |
| return (obj.trait_method(7), obj.trait_prop) | |
| def cross_module_inherited_from_native(obj: SubclassOfNativeBase) -> tuple[int, int, int, int]: | |
| return (obj.base_method(5), obj.base_prop, obj.computed_base_prop, obj.sub_method(3)) | |
| def cross_module_inherited_from_trait(obj: SubclassOfTrait) -> tuple[int, int, int]: | |
| return (obj.trait_method(7), obj.trait_prop, obj.sub_value(2)) | |
| [file other.py] | |
| from collections.abc import Iterator | |
| from typing import Callable, TypeVar, final | |
| from mypy_extensions import mypyc_attr, trait | |
| def times_two(fn: Callable[[FinalMethods, int], int]) -> Callable[[FinalMethods, int], int]: | |
| def inner(self, value: int) -> int: | |
| return fn(self, value) * 2 | |
| return inner | |
| @mypyc_attr(allow_interpreted_subclasses=True) | |
| class FinalMethods: | |
| def __init__(self, base: int) -> None: | |
| self.base = base | |
| self._prop_value = base * 2 | |
| self._computed = base * 3 | |
| @final | |
| def regular(self, value: int) -> int: | |
| return self.base + value | |
| @classmethod | |
| @final | |
| def class_method(cls, value: int) -> int: | |
| return value + 20 | |
| @staticmethod | |
| @final | |
| def static_method(value: int) -> int: | |
| return value + 30 | |
| @final | |
| async def async_method(self, value: int) -> int: | |
| return self.base + value + 40 | |
| @classmethod | |
| @final | |
| async def async_class_method(cls, value: int) -> int: | |
| return value + 70 | |
| @staticmethod | |
| @final | |
| async def async_static_method(value: int) -> int: | |
| return value + 80 | |
| @final | |
| def generator(self, value: int) -> Iterator[int]: | |
| yield self.base + value + 50 | |
| yield self.base + value + 60 | |
| @final | |
| @times_two | |
| def decorated_final(self, value: int) -> int: | |
| return self.base + value + 90 | |
| @property | |
| @final | |
| def final_prop(self) -> int: | |
| return self._prop_value | |
| @property | |
| @final | |
| def computed_prop(self) -> int: | |
| return self._computed + 5 | |
| @mypyc_attr(allow_interpreted_subclasses=True) | |
| class NativeBaseWithFinals: | |
| def __init__(self, value: int) -> None: | |
| self._value = value | |
| self._base_computed = value * 2 | |
| @final | |
| def base_method(self, x: int) -> int: | |
| return self._value + x | |
| @property | |
| @final | |
| def base_prop(self) -> int: | |
| return self._value | |
| @property | |
| @final | |
| def computed_base_prop(self) -> int: | |
| return self._base_computed + 10 | |
| @trait | |
| class FinalTrait: | |
| def __init__(self) -> None: | |
| self._trait_value = 100 | |
| @final | |
| def trait_method(self, x: int) -> int: | |
| return self._trait_value + x | |
| @property | |
| @final | |
| def trait_prop(self) -> int: | |
| return self._trait_value | |
| class SubclassOfNativeBase(NativeBaseWithFinals): | |
| def sub_method(self, x: int) -> int: | |
| return x * 10 | |
| class SubclassOfTrait(FinalTrait): | |
| def __init__(self) -> None: | |
| FinalTrait.__init__(self) | |
| def sub_value(self, x: int) -> int: | |
| return x + 200 | |
| def same_module_calls(obj: FinalMethods) -> tuple[int, int, int, int, int, int, int]: | |
| return ( | |
| obj.regular(2), | |
| obj.class_method(2), | |
| obj.static_method(2), | |
| sum(obj.generator(2)), | |
| FinalMethods.class_method(3), | |
| FinalMethods.static_method(3), | |
| obj.decorated_final(2), | |
| ) | |
| async def same_module_async(obj: FinalMethods) -> tuple[int, int, int, int, int]: | |
| return ( | |
| await obj.async_method(2), | |
| await obj.async_class_method(2), | |
| await obj.async_static_method(2), | |
| await FinalMethods.async_class_method(3), | |
| await FinalMethods.async_static_method(3), | |
| ) | |
| def same_module_property_calls(obj: FinalMethods) -> tuple[int, int]: | |
| return (obj.final_prop, obj.computed_prop) | |
| def same_module_native_base_calls(obj: NativeBaseWithFinals) -> tuple[int, int, int]: | |
| return (obj.base_method(5), obj.base_prop, obj.computed_base_prop) | |
| def same_module_trait_calls(obj: FinalTrait) -> tuple[int, int]: | |
| return (obj.trait_method(7), obj.trait_prop) | |
| def same_module_inherited_from_native(obj: SubclassOfNativeBase) -> tuple[int, int, int, int]: | |
| return (obj.base_method(5), obj.base_prop, obj.computed_base_prop, obj.sub_method(3)) | |
| def same_module_inherited_from_trait(obj: SubclassOfTrait) -> tuple[int, int, int]: | |
| return (obj.trait_method(7), obj.trait_prop, obj.sub_value(2)) | |
| [file driver.py] | |
| import asyncio | |
| from native import ( | |
| cross_module_calls, cross_module_async, cross_module_property_calls, | |
| cross_module_native_base_calls, cross_module_trait_calls, | |
| cross_module_inherited_from_native, cross_module_inherited_from_trait | |
| ) | |
| from other import ( | |
| FinalMethods, NativeBaseWithFinals, SubclassOfNativeBase, SubclassOfTrait, | |
| same_module_calls, same_module_async, same_module_property_calls, | |
| same_module_native_base_calls, same_module_trait_calls, | |
| same_module_inherited_from_native, same_module_inherited_from_trait | |
| ) | |
| obj = FinalMethods(10) | |
| expected = (12, 22, 32, 134, 23, 33, 204) | |
| assert same_module_calls(obj) == expected | |
| assert cross_module_calls(obj) == expected | |
| expected_async = (52, 72, 82, 73, 83) | |
| assert asyncio.run(same_module_async(obj)) == expected_async | |
| assert asyncio.run(cross_module_async(obj)) == expected_async | |
| expected_props = (20, 35) | |
| assert same_module_property_calls(obj) == expected_props | |
| assert cross_module_property_calls(obj) == expected_props | |
| base_obj = NativeBaseWithFinals(15) | |
| expected_base = (20, 15, 40) | |
| assert same_module_native_base_calls(base_obj) == expected_base | |
| assert cross_module_native_base_calls(base_obj) == expected_base | |
| sub_native = SubclassOfNativeBase(25) | |
| expected_sub_native = (30, 25, 60, 30) | |
| assert same_module_inherited_from_native(sub_native) == expected_sub_native | |
| assert cross_module_inherited_from_native(sub_native) == expected_sub_native | |
| sub_trait = SubclassOfTrait() | |
| expected_sub_trait = (107, 100, 202) | |
| assert same_module_inherited_from_trait(sub_trait) == expected_sub_trait | |
| assert cross_module_inherited_from_trait(sub_trait) == expected_sub_trait | |
| [case testFinalMethodsWithInterpretedSubclassesAndNestedInheritance] | |
| from other import BaseWithFinals, CompiledMiddle | |
| def call_final_through_base(obj: BaseWithFinals) -> tuple[int, int, int]: | |
| return (obj.final_method(5), obj.final_prop, obj.nested_final()) | |
| def call_final_through_middle(obj: CompiledMiddle) -> tuple[int, int, int, int]: | |
| return (obj.final_method(5), obj.final_prop, obj.nested_final(), obj.middle_method()) | |
| [file other.py] | |
| from typing import final | |
| from mypy_extensions import mypyc_attr | |
| @mypyc_attr(allow_interpreted_subclasses=True) | |
| class BaseWithFinals: | |
| def __init__(self, value: int) -> None: | |
| self._value = value | |
| self._prop = value * 2 | |
| @final | |
| def final_method(self, x: int) -> int: | |
| return self._value + x | |
| @property | |
| @final | |
| def final_prop(self) -> int: | |
| return self._prop | |
| @final | |
| def nested_final(self) -> int: | |
| return self.final_method(10) + self.final_prop | |
| @mypyc_attr(allow_interpreted_subclasses=True) | |
| class CompiledMiddle(BaseWithFinals): | |
| def middle_method(self) -> int: | |
| return self.final_method(3) + self.final_prop | |
| def same_module_base_calls(obj: BaseWithFinals) -> tuple[int, int, int]: | |
| return (obj.final_method(5), obj.final_prop, obj.nested_final()) | |
| def same_module_middle_calls(obj: CompiledMiddle) -> tuple[int, int, int, int]: | |
| return (obj.final_method(5), obj.final_prop, obj.nested_final(), obj.middle_method()) | |
| [file interpreted_subclass.py] | |
| from other import CompiledMiddle | |
| class InterpretedSubclass(CompiledMiddle): | |
| def interpreted_method(self) -> int: | |
| return self.final_method(7) + self.final_prop | |
| [file driver.py] | |
| from native import call_final_through_base, call_final_through_middle | |
| from other import BaseWithFinals, CompiledMiddle, same_module_base_calls, same_module_middle_calls | |
| from interpreted_subclass import InterpretedSubclass | |
| base = BaseWithFinals(10) | |
| expected_base = (15, 20, 40) | |
| assert same_module_base_calls(base) == expected_base | |
| assert call_final_through_base(base) == expected_base | |
| middle = CompiledMiddle(15) | |
| expected_middle = (20, 30, 55, 48) | |
| assert same_module_middle_calls(middle) == expected_middle | |
| assert call_final_through_middle(middle) == expected_middle | |
| interpreted = InterpretedSubclass(20) | |
| assert interpreted.final_method(5) == 25 | |
| assert interpreted.final_prop == 40 | |
| assert interpreted.nested_final() == 70 | |
| assert interpreted.middle_method() == 63 | |
| assert interpreted.interpreted_method() == 67 | |
| assert call_final_through_base(interpreted) == (25, 40, 70) | |
| assert call_final_through_middle(interpreted) == (25, 40, 70, 63) | |
| [case testCallFunctionInLazilyImportedModule] | |
| import my_lib | |
| def get_version() -> str: | |
| return my_lib.version() | |
| [file my_lib.py] | |
| def version() -> str: | |
| return "1.0.0" | |
| [file other.py] | |
| def lazy_import() -> str: | |
| import native | |
| return native.get_version() | |
| [file driver.py] | |
| from threading import Barrier, Thread | |
| import other | |
| def test_lazy_import() -> None: | |
| barrier = Barrier(2) | |
| def run_once() -> None: | |
| barrier.wait() | |
| assert other.lazy_import() == "1.0.0" | |
| threads = [] | |
| for _ in range(2): | |
| t = Thread(target = run_once) | |
| threads.append(t) | |
| t.start() | |
| for t in threads: | |
| t.join() | |
| test_lazy_import() | |
| [case testConcurrentLazyNativeImportForms] | |
| # separate: [(["native.py", "other_dependency.py", "other_importer.py"], "testgroup")] | |
| from time import sleep | |
| sleep(0.05) | |
| import other_dependency | |
| def get_value() -> int: | |
| return other_dependency.value | |
| [file other_dependency.py] | |
| value = 42 | |
| [file other_importer.py] | |
| def by_module() -> int: | |
| import native | |
| return native.get_value() | |
| def by_from() -> int: | |
| from native import get_value | |
| return get_value() | |
| def by_from_alias() -> int: | |
| from native import get_value as load_value | |
| return load_value() | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| from threading import Barrier | |
| import other_importer | |
| functions = [ | |
| other_importer.by_module, | |
| other_importer.by_from, | |
| other_importer.by_from_alias, | |
| ] | |
| barrier = Barrier(len(functions)) | |
| def run(function): | |
| barrier.wait() | |
| return function() | |
| with ThreadPoolExecutor(max_workers=len(functions)) as executor: | |
| futures = [executor.submit(run, function) for function in functions] | |
| assert [future.result() for future in futures] == [42] * len(functions) | |
| [case testConcurrentLazyNativePackageImportForms] | |
| # separate: [(["other_pkg/__init__.py", "other_pkg/other_target.py", "other_pkg/other_importer.py"], "testgroup")] | |
| pass | |
| [file other_pkg/__init__.py] | |
| [file other_pkg/other_target.py] | |
| from time import sleep | |
| sleep(0.05) | |
| import py_dependency | |
| def get_value() -> int: | |
| return py_dependency.value | |
| [file other_pkg/other_importer.py] | |
| def by_dotted_module() -> int: | |
| import other_pkg.other_target | |
| return other_pkg.other_target.get_value() | |
| def by_dotted_alias() -> int: | |
| import other_pkg.other_target as target | |
| return target.get_value() | |
| def by_from_package() -> int: | |
| from other_pkg import other_target | |
| return other_target.get_value() | |
| def by_from_module() -> int: | |
| from other_pkg.other_target import get_value | |
| return get_value() | |
| def by_relative_package() -> int: | |
| from . import other_target | |
| return other_target.get_value() | |
| def by_relative_module() -> int: | |
| from .other_target import get_value | |
| return get_value() | |
| [file py_dependency.py] | |
| value = 42 | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| from threading import Barrier | |
| from other_pkg import other_importer | |
| functions = [ | |
| other_importer.by_dotted_module, | |
| other_importer.by_dotted_alias, | |
| other_importer.by_from_package, | |
| other_importer.by_from_module, | |
| other_importer.by_relative_package, | |
| other_importer.by_relative_module, | |
| ] | |
| barrier = Barrier(len(functions)) | |
| def run(function): | |
| barrier.wait() | |
| return function() | |
| with ThreadPoolExecutor(max_workers=len(functions)) as executor: | |
| futures = [executor.submit(run, function) for function in functions] | |
| assert [future.result() for future in futures] == [42] * len(functions) | |
| [case testConcurrentLazyNativeImportFromInterpretedModules] | |
| from time import sleep | |
| sleep(0.05) | |
| import py_dependency | |
| def get_value() -> int: | |
| return py_dependency.value | |
| [file py_dependency.py] | |
| value = 42 | |
| [file py_importer.py] | |
| def by_module(): | |
| import native | |
| return native.get_value() | |
| def by_from(): | |
| from native import get_value | |
| return get_value() | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| from threading import Barrier | |
| import py_importer | |
| functions = [py_importer.by_module, py_importer.by_from] | |
| barrier = Barrier(len(functions)) | |
| def run(function): | |
| barrier.wait() | |
| return function() | |
| with ThreadPoolExecutor(max_workers=len(functions)) as executor: | |
| futures = [executor.submit(run, function) for function in functions] | |
| assert [future.result() for future in futures] == [42] * len(functions) | |
| [case testConcurrentLazyNativeImportFromNativeAndInterpretedModules] | |
| # separate: [(["native.py", "other_importer.py"], "testgroup")] | |
| from time import sleep | |
| sleep(0.05) | |
| import py_dependency | |
| def get_value() -> int: | |
| return py_dependency.value | |
| [file other_importer.py] | |
| def load() -> int: | |
| import native | |
| return native.get_value() | |
| [file py_dependency.py] | |
| value = 42 | |
| [file py_importer.py] | |
| def load(): | |
| from native import get_value | |
| return get_value() | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| from threading import Barrier | |
| import other_importer | |
| import py_importer | |
| functions = [other_importer.load, py_importer.load] | |
| barrier = Barrier(len(functions)) | |
| def run(function): | |
| barrier.wait() | |
| return function() | |
| with ThreadPoolExecutor(max_workers=len(functions)) as executor: | |
| futures = [executor.submit(run, function) for function in functions] | |
| assert [future.result() for future in futures] == [42] * len(functions) | |
| [case testConcurrentLazyNativeImportAcrossCompilationGroups] | |
| # separate: [(["native.py", "other_import_a.py"], "target"), (["other_import_b.py"], "importer_b")] | |
| from time import sleep | |
| sleep(0.05) | |
| def get_value() -> int: | |
| return 42 | |
| [file other_import_a.py] | |
| def load() -> int: | |
| import native | |
| return native.get_value() | |
| [file other_import_b.py] | |
| def load() -> int: | |
| from native import get_value | |
| return get_value() | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| from threading import Barrier | |
| import other_import_a | |
| import other_import_b | |
| functions = [other_import_a.load, other_import_b.load] | |
| barrier = Barrier(len(functions)) | |
| def run(function): | |
| barrier.wait() | |
| return function() | |
| with ThreadPoolExecutor(max_workers=len(functions)) as executor: | |
| futures = [executor.submit(run, function) for function in functions] | |
| assert [future.result() for future in futures] == [42] * len(functions) | |
| [case testTopLevelCrossGroupImportWaitsAfterCircularImport] | |
| # separate: [(["other_target.py"], "target_group"), (["other_blocker.py", "other_top_level_importer.py"], "importer_group")] | |
| pass | |
| [file other_target.py] | |
| import import_sync | |
| early_value = 41 | |
| import_sync.target_started.set() | |
| assert import_sync.blocker_started.wait(timeout=15) | |
| import_sync.target_importing_blocker.set() | |
| import other_blocker | |
| import_sync.target_waiting_to_finish.set() | |
| assert import_sync.target_may_finish.wait(timeout=15) | |
| value = 42 | |
| [file other_blocker.py] | |
| import import_sync | |
| import_sync.blocker_started.set() | |
| assert import_sync.blocker_may_import_target.wait(timeout=15) | |
| import other_target | |
| saw_partial_target = not hasattr(other_target, "value") | |
| partial_value = other_target.early_value | |
| [file other_top_level_importer.py] | |
| import import_sync | |
| import_sync.top_level_started.set() | |
| import other_target | |
| saw_partial_target = not hasattr(other_target, "value") | |
| [file import_sync.py] | |
| from threading import Event | |
| target_started = Event() | |
| blocker_started = Event() | |
| target_importing_blocker = Event() | |
| blocker_may_import_target = Event() | |
| target_waiting_to_finish = Event() | |
| top_level_started = Event() | |
| target_may_finish = Event() | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| import importlib | |
| from time import monotonic, sleep | |
| import import_sync | |
| with ThreadPoolExecutor(max_workers=3) as executor: | |
| target_future = executor.submit(importlib.import_module, "other_target") | |
| assert import_sync.target_started.wait(timeout=15) | |
| blocker_future = executor.submit(importlib.import_module, "other_blocker") | |
| assert import_sync.target_importing_blocker.wait(timeout=15) | |
| bootstrap = importlib.import_module("importlib._bootstrap") | |
| blocker_lock = bootstrap._get_module_lock("other_blocker") | |
| deadline = monotonic() + 5 | |
| while not blocker_lock.waiters and monotonic() < deadline: | |
| sleep(0.001) | |
| target_was_waiting = bool(blocker_lock.waiters) | |
| import_sync.blocker_may_import_target.set() | |
| assert target_was_waiting | |
| blocker = blocker_future.result(timeout=10) | |
| assert blocker.saw_partial_target | |
| assert blocker.partial_value == 41 | |
| assert import_sync.target_waiting_to_finish.wait(timeout=15) | |
| top_level_future = executor.submit(importlib.import_module, "other_top_level_importer") | |
| assert import_sync.top_level_started.wait(timeout=15) | |
| target_lock = bootstrap._get_module_lock("other_target") | |
| deadline = monotonic() + 5 | |
| while not target_lock.waiters and not top_level_future.done() and monotonic() < deadline: | |
| sleep(0.001) | |
| top_level_waited = bool(target_lock.waiters) | |
| import_sync.target_may_finish.set() | |
| target = target_future.result(timeout=10) | |
| top_level_importer = top_level_future.result(timeout=10) | |
| assert top_level_waited | |
| assert target.value == 42 | |
| assert not top_level_importer.saw_partial_target | |
| [case testRegularImportWaitsForDirectNativeImport] | |
| # separate: [(["native.py", "other_importer.py"], "testgroup")] | |
| from time import sleep | |
| import import_sync | |
| import_sync.direct_started.set() | |
| assert import_sync.regular_started.wait(timeout=15) | |
| sleep(0.05) | |
| def get_value() -> int: | |
| return 42 | |
| [file import_sync.py] | |
| from threading import Event | |
| direct_started = Event() | |
| regular_started = Event() | |
| [file other_importer.py] | |
| def load() -> int: | |
| import native | |
| return native.get_value() | |
| [file py_importer.py] | |
| import import_sync | |
| def load(): | |
| import_sync.regular_started.set() | |
| import native | |
| return native.get_value() | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| import import_sync | |
| import other_importer | |
| import py_importer | |
| with ThreadPoolExecutor(max_workers=2) as executor: | |
| direct_future = executor.submit(other_importer.load) | |
| assert import_sync.direct_started.wait(timeout=15) | |
| regular_future = executor.submit(py_importer.load) | |
| assert direct_future.result(timeout=10) == 42 | |
| assert regular_future.result(timeout=10) == 42 | |
| [case testConcurrentFailedLazyNativeImportRetries] | |
| # separate: [(["native.py", "other_importer.py"], "testgroup")] | |
| from time import sleep | |
| import failure_state | |
| failure_state.attempts += 1 | |
| sleep(0.05) | |
| if failure_state.attempts == 1: | |
| raise RuntimeError("first initialization failed") | |
| def get_value() -> int: | |
| return 42 | |
| [file failure_state.py] | |
| attempts = 0 | |
| [file other_importer.py] | |
| def load() -> int: | |
| from native import get_value | |
| return get_value() | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| from threading import Barrier | |
| import failure_state | |
| import other_importer | |
| barrier = Barrier(2) | |
| def run(): | |
| barrier.wait() | |
| return other_importer.load() | |
| with ThreadPoolExecutor(max_workers=2) as executor: | |
| futures = [executor.submit(run) for _ in range(2)] | |
| values = [] | |
| errors = [] | |
| for future in futures: | |
| try: | |
| values.append(future.result()) | |
| except RuntimeError as error: | |
| errors.append(str(error)) | |
| assert values == [42] | |
| assert errors == ["first initialization failed"] | |
| assert failure_state.attempts == 2 | |
| assert other_importer.load() == 42 | |
| [case testFailedConcurrentCircularNativeImportRefreshesCache] | |
| # separate: [(["native.py", "other_a.py", "other_b.py"], "testgroup")] | |
| pass | |
| [file import_sync.py] | |
| from threading import Event | |
| a_started = Event() | |
| b_started = Event() | |
| a_importing_b = Event() | |
| b_waiting_for_driver = Event() | |
| b_may_import_a = Event() | |
| [file failure_state.py] | |
| attempts = 0 | |
| [file other_a.py] | |
| import failure_state | |
| failure_state.attempts += 1 | |
| if failure_state.attempts == 1: | |
| import import_sync | |
| import_sync.a_started.set() | |
| assert import_sync.b_started.wait(timeout=15) | |
| import_sync.a_importing_b.set() | |
| import other_b | |
| raise RuntimeError("first initialization failed") | |
| value = 42 | |
| [file other_b.py] | |
| import import_sync | |
| import_sync.b_started.set() | |
| assert import_sync.a_started.wait(timeout=15) | |
| assert import_sync.a_importing_b.wait(timeout=15) | |
| import_sync.b_waiting_for_driver.set() | |
| assert import_sync.b_may_import_a.wait(timeout=15) | |
| import other_a | |
| saw_partial_a = not hasattr(other_a, "value") | |
| def get_a_value() -> int: | |
| return other_a.value | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| import importlib | |
| from time import monotonic, sleep | |
| from testutil import assertRaises | |
| import failure_state | |
| import import_sync | |
| import native # Preload the compilation group's shared library. | |
| with ThreadPoolExecutor(max_workers=2) as executor: | |
| future_a = executor.submit(importlib.import_module, "other_a") | |
| assert import_sync.a_started.wait(timeout=15) | |
| future_b = executor.submit(importlib.import_module, "other_b") | |
| assert import_sync.a_importing_b.wait(timeout=15) | |
| assert import_sync.b_waiting_for_driver.wait(timeout=15) | |
| # Wait until other_a is blocked on other_b's module lock. Letting other_b | |
| # import other_a then deterministically closes the lock cycle and returns | |
| # other_a's partial module. | |
| bootstrap = importlib.import_module("importlib._bootstrap") | |
| lock = bootstrap._get_module_lock("other_b") | |
| deadline = monotonic() + 5 | |
| while not lock.waiters and monotonic() < deadline: | |
| sleep(0.001) | |
| has_waiter = bool(lock.waiters) | |
| import_sync.b_may_import_a.set() | |
| assert has_waiter | |
| with assertRaises(RuntimeError, "first initialization failed"): | |
| future_a.result(timeout=10) | |
| other_b = future_b.result(timeout=10) | |
| assert failure_state.attempts == 1 | |
| assert other_b.saw_partial_a | |
| other_a = importlib.import_module("other_a") | |
| assert failure_state.attempts == 2 | |
| assert other_a.value == 42 | |
| assert other_b.get_a_value() == 42 | |
| [case testConcurrentCircularNativeImports] | |
| # separate: [(["other_a.py", "other_b.py"], "testgroup")] | |
| pass | |
| [file import_sync.py] | |
| from threading import Barrier | |
| barrier = Barrier(2) | |
| [file other_a.py] | |
| from import_sync import barrier | |
| def value() -> str: | |
| return "a" | |
| barrier.wait(timeout=15) | |
| import other_b | |
| other_value = other_b.value() | |
| [file other_b.py] | |
| from import_sync import barrier | |
| def value() -> str: | |
| return "b" | |
| barrier.wait(timeout=15) | |
| import other_a | |
| other_value = other_a.value() | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| import importlib | |
| with ThreadPoolExecutor(max_workers=2) as executor: | |
| future_a = executor.submit(importlib.import_module, "other_a") | |
| future_b = executor.submit(importlib.import_module, "other_b") | |
| other_a = future_a.result(timeout=15) | |
| other_b = future_b.result(timeout=15) | |
| assert other_a.other_value == "b" | |
| assert other_b.other_value == "a" | |
| [case testConcurrentCircularNativeFromImports] | |
| # separate: [(["other_a.py", "other_b.py"], "testgroup")] | |
| pass | |
| [file import_sync.py] | |
| from threading import Barrier | |
| barrier = Barrier(2) | |
| [file other_a.py] | |
| from import_sync import barrier | |
| def value() -> str: | |
| return "a" | |
| barrier.wait(timeout=15) | |
| from other_b import value as other_value_fn | |
| other_value = other_value_fn() | |
| [file other_b.py] | |
| from import_sync import barrier | |
| def value() -> str: | |
| return "b" | |
| barrier.wait(timeout=15) | |
| from other_a import value as other_value_fn | |
| other_value = other_value_fn() | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| import importlib | |
| with ThreadPoolExecutor(max_workers=2) as executor: | |
| future_a = executor.submit(importlib.import_module, "other_a") | |
| future_b = executor.submit(importlib.import_module, "other_b") | |
| other_a = future_a.result(timeout=15) | |
| other_b = future_b.result(timeout=15) | |
| assert other_a.other_value == "b" | |
| assert other_b.other_value == "a" | |
| [case testNativeModuleReimportBehavior] | |
| value = 42 | |
| def get_value() -> int: | |
| return value | |
| [file driver.py] | |
| import importlib | |
| import sys | |
| from testutil import assertRaises | |
| import native | |
| first = native | |
| assert first.get_value() == 42 | |
| del sys.modules["native"] | |
| if hasattr(sys, "_is_gil_enabled") and not sys._is_gil_enabled(): | |
| with assertRaises(ImportError, "native module 'native' does not support reinitialization"): | |
| importlib.import_module("native") | |
| assert "native" not in sys.modules | |
| else: | |
| # Legacy single-phase initialization returns the original module object. | |
| second = importlib.import_module("native") | |
| assert second is first | |
| assert first.get_value() == 42 | |
| [case testCachedPartialNativeModuleDoesNotReexecute] | |
| # separate: [(["native.py", "other_target.py", "other_blocker.py"], "testgroup")] | |
| def load_target() -> int: | |
| import other_target | |
| return other_target.value | |
| [file execution_state.py] | |
| attempts = 0 | |
| [file other_target.py] | |
| import execution_state | |
| execution_state.attempts += 1 | |
| import other_blocker | |
| value = 42 | |
| [file other_blocker.py] | |
| # Cache other_target's partial module while its regular import is running. | |
| import other_target | |
| [file driver.py] | |
| import importlib | |
| import sys | |
| import execution_state | |
| import native | |
| from testutil import assertRaises | |
| target = importlib.import_module("other_target") | |
| assert target.value == 42 | |
| assert execution_state.attempts == 1 | |
| del sys.modules["other_target"] | |
| with assertRaises( | |
| ImportError, "initialized native module 'other_target' is missing from sys.modules" | |
| ): | |
| native.load_target() | |
| assert execution_state.attempts == 1 | |
| [case testTopLevelThreadImportsNativeModuleFromSameGroup] | |
| # separate: [(["native.py", "other_target.py"], "testgroup")] | |
| from threading import Thread | |
| results: list[int] = [] | |
| def load_target() -> None: | |
| import other_target | |
| results.append(other_target.value) | |
| thread = Thread(target=load_target) | |
| thread.start() | |
| thread.join(timeout=15) | |
| assert not thread.is_alive(), "native import blocked on its compilation unit" | |
| assert results == [42] | |
| [file other_target.py] | |
| value = 42 | |
| [file driver.py] | |
| import native | |
| assert native.results == [42] | |
| [case testCallFunctionInLazilyImportedModuleThroughAny] | |
| [file my_lib.py] | |
| def version() -> str: | |
| return "1.0.0" | |
| [file other_pkg/__init__.py] | |
| [file other_pkg/other_callmylib.py] | |
| import my_lib | |
| def get_version() -> str: | |
| return my_lib.version() | |
| [file other_pkg/other_import.py] | |
| from typing import Any | |
| def lazy_import() -> str: | |
| import other_pkg.other_callmylib | |
| pkg: Any = other_pkg | |
| return pkg.other_callmylib.get_version() | |
| [file driver.py] | |
| from threading import Barrier, Thread | |
| import other_pkg.other_import | |
| def test_lazy_import() -> None: | |
| barrier = Barrier(2) | |
| def run_once() -> None: | |
| barrier.wait() | |
| assert other_pkg.other_import.lazy_import() == "1.0.0" | |
| threads = [] | |
| for _ in range(2): | |
| t = Thread(target = run_once) | |
| threads.append(t) | |
| t.start() | |
| for t in threads: | |
| t.join() | |
| test_lazy_import() | |
| [case testVerifiedNonNativeImportCacheSkipsModuleSpec] | |
| def load() -> int: | |
| import dependency | |
| return dependency.value | |
| [file cache_state.py] | |
| spec_checks = 0 | |
| [file dependency.py] | |
| import cache_state | |
| class TrackingSpec: | |
| def __getattribute__(self, name: str): | |
| if name == "_initializing": | |
| cache_state.spec_checks += 1 | |
| return False | |
| raise AttributeError(name) | |
| __spec__ = TrackingSpec() | |
| value = 42 | |
| [file driver.py] | |
| import cache_state | |
| import native | |
| assert native.load() == 42 | |
| checks_after_first_import = cache_state.spec_checks | |
| assert checks_after_first_import > 0 | |
| assert native.load() == 42 | |
| assert cache_state.spec_checks == checks_after_first_import | |
| [case testConcurrentNativeImportDoesNotLeakCacheReference] | |
| # separate: [(["native.py", "other_target.py", "other_importer.py"], "testgroup")] | |
| from time import sleep | |
| sleep(0.05) | |
| def value() -> int: | |
| return 42 | |
| [file other_target.py] | |
| def value() -> int: | |
| return 42 | |
| [file other_importer.py] | |
| def load_native() -> int: | |
| import native | |
| return native.value() | |
| def load_target() -> int: | |
| import other_target | |
| return other_target.value() | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| from sys import getrefcount, modules | |
| from threading import Barrier | |
| import other_importer | |
| barrier = Barrier(2) | |
| def load_native() -> int: | |
| barrier.wait() | |
| return other_importer.load_native() | |
| with ThreadPoolExecutor(max_workers=2) as executor: | |
| futures = [executor.submit(load_native) for _ in range(2)] | |
| assert [future.result() for future in futures] == [42, 42] | |
| assert other_importer.load_target() == 42 | |
| assert getrefcount(modules["native"]) == getrefcount(modules["other_target"]) | |
| [case testNativeModuleCanReplaceSpecDuringRegularImport] | |
| assert __spec__ is not None | |
| body_spec = __spec__ | |
| __spec__ = None | |
| value = 42 | |
| [file driver.py] | |
| import native | |
| assert native.value == 42 | |
| assert native.body_spec._initializing is False | |
| [case testReplacedSpecDoesNotPublishPartialNativeModule] | |
| # separate: [(["native.py", "other_target.py", "other_blocker.py"], "testgroup")] | |
| import import_sync | |
| def read_target() -> int: | |
| import_sync.reader_started.set() | |
| import other_target | |
| return other_target.final_value | |
| [file import_sync.py] | |
| from threading import Event | |
| partial_cached = Event() | |
| reader_started = Event() | |
| blocker_may_return = Event() | |
| [file other_target.py] | |
| import import_sync | |
| assert __spec__ is not None | |
| body_spec = __spec__ | |
| __spec__ = None | |
| early_value = 41 | |
| import other_blocker | |
| final_value = 42 | |
| [file other_blocker.py] | |
| import import_sync | |
| import other_target | |
| assert other_target.early_value == 41 | |
| assert not hasattr(other_target, "final_value") | |
| import_sync.partial_cached.set() | |
| assert import_sync.blocker_may_return.wait(timeout=15) | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| import importlib | |
| from time import monotonic, sleep | |
| import import_sync | |
| import native | |
| with ThreadPoolExecutor(max_workers=2) as executor: | |
| target_future = executor.submit(importlib.import_module, "other_target") | |
| assert import_sync.partial_cached.wait(timeout=15) | |
| reader_future = executor.submit(native.read_target) | |
| assert import_sync.reader_started.wait(timeout=15) | |
| bootstrap = importlib.import_module("importlib._bootstrap") | |
| lock = bootstrap._get_module_lock("other_target") | |
| deadline = monotonic() + 5 | |
| while not lock.waiters and not reader_future.done() and monotonic() < deadline: | |
| sleep(0.001) | |
| reader_waited = bool(lock.waiters) | |
| import_sync.blocker_may_return.set() | |
| target = target_future.result(timeout=15) | |
| value = reader_future.result(timeout=15) | |
| assert reader_waited | |
| assert target.final_value == 42 | |
| assert target.body_spec._initializing is False | |
| assert value == 42 | |
| [case testNativeModuleCanReplaceSpecDuringDirectImport] | |
| # separate: [(["native.py", "other_importer.py"], "testgroup")] | |
| assert __spec__ is not None | |
| body_spec = __spec__ | |
| __spec__ = None | |
| value = 42 | |
| [file other_importer.py] | |
| def load() -> int: | |
| import native | |
| return native.value | |
| [file driver.py] | |
| import other_importer | |
| assert other_importer.load() == 42 | |
| assert __import__("native").__spec__ is None | |
| assert __import__("native").body_spec._initializing is False | |
| [case testNativeModuleReplacingSpecClearsOriginalSpecOnFailure] | |
| # separate: [(["native.py", "other_importer.py"], "testgroup")] | |
| import spec_state | |
| assert __spec__ is not None | |
| spec_state.specs.append(__spec__) | |
| __spec__ = None | |
| raise RuntimeError("initialization failed") | |
| [file spec_state.py] | |
| from typing import Any | |
| specs: list[Any] = [] | |
| [file other_importer.py] | |
| def load() -> None: | |
| import native | |
| [file driver.py] | |
| import sys | |
| import other_importer | |
| import spec_state | |
| from testutil import assertRaises | |
| with assertRaises(RuntimeError, "initialization failed"): | |
| other_importer.load() | |
| assert spec_state.specs[0]._initializing is False | |
| assert "native" not in sys.modules | |
| with assertRaises(RuntimeError, "initialization failed"): | |
| import native | |
| assert len(spec_state.specs) == 2 | |
| assert spec_state.specs[1]._initializing is False | |
| assert "native" not in sys.modules | |
| [case testNativeModuleDoesNotReexecuteAfterFinalizationFailure] | |
| # separate: [(["native.py", "other_target.py"], "testgroup")] | |
| def load_target() -> None: | |
| import other_target | |
| [file execution_state.py] | |
| attempts = 0 | |
| [file other_target.py] | |
| import execution_state | |
| import spec_hook | |
| execution_state.attempts += 1 | |
| assert __spec__ is not None | |
| spec_hook.reject_clearing(__spec__) | |
| [file spec_hook.py] | |
| from typing import Any | |
| def reject_clearing(original_spec: Any) -> None: | |
| spec_type: Any = type(original_spec) | |
| original_setattr: Any = spec_type.__setattr__ | |
| def reject_original_spec_clear(instance: Any, name: str, value: Any) -> None: | |
| if instance is original_spec and name == "_initializing" and value is False: | |
| raise RuntimeError("cannot finish initialization") | |
| original_setattr(instance, name, value) | |
| spec_type.__setattr__ = reject_original_spec_clear | |
| [file driver.py] | |
| import sys | |
| import execution_state | |
| import native | |
| from testutil import assertRaises | |
| with assertRaises(RuntimeError, "cannot finish initialization"): | |
| native.load_target() | |
| assert execution_state.attempts == 1 | |
| assert "other_target" not in sys.modules | |
| with assertRaises(ImportError, "native module 'other_target' does not support reinitialization"): | |
| native.load_target() | |
| assert execution_state.attempts == 1 | |
| assert "other_target" not in sys.modules | |
| [case testNormalNativeImportPublishesParentAttributeOnce] | |
| pass | |
| [file pkg/__init__.py] | |
| from sys import modules | |
| from types import ModuleType | |
| from typing import Any | |
| child_setattr_calls = 0 | |
| class TrackingModule(ModuleType): | |
| def __setattr__(self, name: str, value: Any) -> None: | |
| if name == "other_child": | |
| self.child_setattr_calls += 1 | |
| ModuleType.__setattr__(self, name, value) | |
| modules[__name__].__class__ = TrackingModule | |
| [file pkg/other_child.py] | |
| value = 42 | |
| [file driver.py] | |
| import importlib | |
| import pkg | |
| child = importlib.import_module("pkg.other_child") | |
| assert child.value == 42 | |
| assert pkg.other_child is child | |
| assert pkg.child_setattr_calls == 1 | |
| [file sys/__init__.pyi] | |
| modules: dict[str, object] | |
| [case testConcurrentNativeImportWaitsForParentBinding] | |
| # separate: [(["native.py", "pkg/other_target.py", "other_blocker.py"], "testgroup")] | |
| import import_sync | |
| def load_target() -> int: | |
| import pkg.other_target | |
| return pkg.other_target.final_value | |
| def read_target() -> int: | |
| import_sync.reader_started.set() | |
| import pkg.other_target | |
| return pkg.other_target.final_value | |
| [file import_sync.py] | |
| from threading import Event | |
| parent_binding_started = Event() | |
| parent_may_bind = Event() | |
| reader_started = Event() | |
| [file pkg/__init__.py] | |
| from sys import modules | |
| from types import ModuleType | |
| from typing import Any | |
| import import_sync | |
| class BlockingModule(ModuleType): | |
| def __setattr__(self, name: str, value: Any) -> None: | |
| if name == "other_target": | |
| import_sync.parent_binding_started.set() | |
| assert import_sync.parent_may_bind.wait(timeout=15) | |
| ModuleType.__setattr__(self, name, value) | |
| modules[__name__].__class__ = BlockingModule | |
| [file pkg/other_target.py] | |
| early_value = 41 | |
| import other_blocker | |
| final_value = 42 | |
| [file other_blocker.py] | |
| # This circular import caches pkg.other_target's partial module in the | |
| # compilation group's module static. | |
| import pkg.other_target | |
| [file driver.py] | |
| from concurrent.futures import ThreadPoolExecutor | |
| import importlib | |
| from time import monotonic, sleep | |
| import import_sync | |
| import native | |
| import pkg | |
| with ThreadPoolExecutor(max_workers=2) as executor: | |
| load_future = executor.submit(native.load_target) | |
| assert import_sync.parent_binding_started.wait(timeout=15) | |
| read_future = executor.submit(native.read_target) | |
| assert import_sync.reader_started.wait(timeout=15) | |
| bootstrap = importlib.import_module("importlib._bootstrap") | |
| target_lock = bootstrap._get_module_lock("pkg.other_target") | |
| deadline = monotonic() + 5 | |
| while not target_lock.waiters and not read_future.done() and monotonic() < deadline: | |
| sleep(0.001) | |
| reader_waited = bool(target_lock.waiters) | |
| import_sync.parent_may_bind.set() | |
| assert reader_waited | |
| assert load_future.result(timeout=15) == 42 | |
| assert read_future.result(timeout=15) == 42 | |
| assert pkg.other_target.final_value == 42 | |
| [file sys/__init__.pyi] | |
| modules: dict[str, object] | |
| [case testDirectNativeImportWarnsWhenParentRejectsAttribute] | |
| # separate: [(["native.py", "pkg/other_child.py"], "testgroup")] | |
| def load() -> int: | |
| from pkg.other_child import value | |
| return value | |
| [file pkg/__init__.py] | |
| from sys import modules | |
| from types import ModuleType | |
| from typing import Any | |
| child_executions = 0 | |
| class RejectingModule(ModuleType): | |
| def __setattr__(self, name: str, value: Any) -> None: | |
| if name == "other_child": | |
| raise AttributeError("child rejected") | |
| ModuleType.__setattr__(self, name, value) | |
| modules[__name__].__class__ = RejectingModule | |
| [file pkg/other_child.py] | |
| import pkg | |
| pkg.child_executions += 1 | |
| value = 42 | |
| [file driver.py] | |
| import sys | |
| import warnings | |
| import native | |
| import pkg | |
| with warnings.catch_warnings(record=True) as caught: | |
| warnings.simplefilter("always") | |
| assert native.load() == 42 | |
| assert native.load() == 42 | |
| assert "pkg.other_child" in sys.modules | |
| assert not hasattr(pkg, "other_child") | |
| assert pkg.child_executions == 1 | |
| assert len(caught) == 1 | |
| assert caught[0].category is ImportWarning | |
| assert str(caught[0].message) == ( | |
| "Cannot set an attribute on 'pkg' for child module 'other_child'" | |
| ) | |
| [file sys/__init__.pyi] | |
| modules: dict[str, object] | |
| [case testNormalNativeImportWarnsWhenParentRejectsAttribute] | |
| pass | |
| [file pkg/__init__.py] | |
| from sys import modules | |
| from types import ModuleType | |
| from typing import Any | |
| class RejectingModule(ModuleType): | |
| def __setattr__(self, name: str, value: Any) -> None: | |
| if name == "other_child": | |
| raise AttributeError("child rejected") | |
| ModuleType.__setattr__(self, name, value) | |
| modules[__name__].__class__ = RejectingModule | |
| [file pkg/other_child.py] | |
| value = 42 | |
| [file driver.py] | |
| import importlib | |
| import sys | |
| import warnings | |
| import pkg | |
| with warnings.catch_warnings(record=True) as caught: | |
| warnings.simplefilter("always") | |
| child = importlib.import_module("pkg.other_child") | |
| assert child.value == 42 | |
| assert sys.modules["pkg.other_child"] is child | |
| assert not hasattr(pkg, "other_child") | |
| assert len(caught) == 1 | |
| assert caught[0].category is ImportWarning | |
| [file sys/__init__.pyi] | |
| modules: dict[str, object] | |
| [case testDirectNativeImportPublishesParentAttributeOnce] | |
| # separate: [(["native.py", "pkg/other_child.py"], "testgroup")] | |
| def load() -> int: | |
| import pkg.other_child | |
| return pkg.other_child.value | |
| [file pkg/__init__.py] | |
| from sys import modules | |
| from types import ModuleType | |
| from typing import Any | |
| child_setattr_calls = 0 | |
| class TrackingModule(ModuleType): | |
| def __setattr__(self, name: str, value: Any) -> None: | |
| if name == "other_child": | |
| self.child_setattr_calls += 1 | |
| ModuleType.__setattr__(self, name, value) | |
| modules[__name__].__class__ = TrackingModule | |
| [file pkg/other_child.py] | |
| value = 42 | |
| [file driver.py] | |
| import builtins | |
| import sys | |
| import native | |
| import pkg | |
| original_import = builtins.__import__ | |
| parent_imports = 0 | |
| def tracking_import(name, globals=None, locals=None, fromlist=(), level=0): | |
| global parent_imports | |
| if name == "pkg": | |
| parent_imports += 1 | |
| return original_import(name, globals, locals, fromlist, level) | |
| builtins.__import__ = tracking_import | |
| try: | |
| assert native.load() == 42 | |
| finally: | |
| builtins.__import__ = original_import | |
| assert parent_imports == 1 | |
| assert pkg.other_child is sys.modules["pkg.other_child"] | |
| assert pkg.child_setattr_calls == 1 | |
| [file sys/__init__.pyi] | |
| modules: dict[str, object] | |
| [case testMultiModuleClassBodyFinal] | |
| from typing import Any | |
| from other import Base | |
| class Sub(Base): | |
| def sub_literal(self) -> int: | |
| return self.LITERAL | |
| def sub_computed(self) -> int: | |
| return self.COMPUTED | |
| def read_through_instance(b: Base) -> int: | |
| return b.LITERAL + b.COMPUTED | |
| def read_through_class() -> int: | |
| return Base.LITERAL + Base.COMPUTED | |
| [file other.py] | |
| from typing import Final | |
| def make() -> int: | |
| return 7 | |
| class Base: | |
| LITERAL: Final = 23 | |
| COMPUTED: Final = make() | |
| ITEMS: Final = [1, 2] | |
| def base_literal(self) -> int: | |
| return self.LITERAL | |
| def base_computed(self) -> int: | |
| return self.COMPUTED | |
| [file driver.py] | |
| from typing import Any | |
| from native import Sub, read_through_instance, read_through_class | |
| from other import Base | |
| # Reading a class-body Final defined in another module, both constant folded | |
| # (LITERAL) and loaded from that module's static (COMPUTED). | |
| assert read_through_instance(Base()) == 30 | |
| assert read_through_class() == 30 | |
| assert Sub().sub_literal() == 23 | |
| assert Sub().sub_computed() == 7 | |
| assert Sub().base_literal() == 23 | |
| assert Sub().base_computed() == 7 | |
| # Dynamic access resolves through the class dict in either module. | |
| o: Any = Sub() | |
| assert o.LITERAL == 23 | |
| assert o.COMPUTED == 7 | |
| assert o.ITEMS == [1, 2] | |
| b: Any = Base() | |
| assert b.COMPUTED == 7 | |
| assert b.ITEMS is Base.ITEMS | |
| [case testImportPackageWithModuleGetattr] | |
| [file other_pkg/__init__.py] | |
| def __getattr__(name: str) -> str: | |
| if name.startswith("__"): | |
| raise AttributeError(name) | |
| return name | |
| [file other_pkg/other_sub.py] | |
| x = 1 | |
| [file driver.py] | |
| import importlib.machinery | |
| import other_pkg.other_sub | |
| assert other_pkg.other_sub.x == 1 | |
| ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES | |
| assert any(other_pkg.__file__.endswith(s) for s in ext_suffixes), other_pkg.__file__ | |
| assert other_pkg.__path__ | |
| assert other_pkg.__spec__ is not None | |
| assert other_pkg.__package__ == "other_pkg" | |
| assert other_pkg.missing == "missing" |