From 96658ee7c62b1f356569b8e5a73ded1f445b6ca5 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Wed, 7 Oct 2026 16:06:19 +0100 Subject: [PATCH] [mypyc] Fix undeclared module in C when base class is a re-export Fixes mypyc/mypyc#1163. Fixes mypyc/mypyc#1155. Fixes mypyc/mypyc#1033. If a non-native class (for example, an enum) had a base class that was imported through a re-export, the generated C failed to compile: ```python from backports.strenum import StrEnum # Defined in backports.strenum.strenum class C(StrEnum): # error: 'CPyModule_backports___strenum___strenum' undeclared x = "x" ``` The base class was loaded from the module where it's defined, but that module wasn't explicitly imported. Subclassing `ctypes.Structure` (defined in `_ctypes`) had the same issue. Now base classes from other modules are loaded using `get_module_attr`, which imports the module if needed. This also fixes two related issues with non-native classes. If the defining module was imported only in a function body that hadn't run yet, the base was looked up from None. A nested class used as a base (such as `Outer.Inner`) generated an undeclared module reference for `Outer`, since the module name was derived from the fullname. --- mypyc/irbuild/classdef.py | 14 ++++-- mypyc/test-data/run-classes.test | 78 +++++++++++++++++++++++++++++++- 2 files changed, 86 insertions(+), 6 deletions(-) diff --git a/mypyc/irbuild/classdef.py b/mypyc/irbuild/classdef.py index a0aa7c4ac26f5..cd3d07a5d3aad 100644 --- a/mypyc/irbuild/classdef.py +++ b/mypyc/irbuild/classdef.py @@ -667,11 +667,17 @@ def populate_non_ext_bases( name = "_NamedTuple" base = builder.get_module_attr("typing", name, cdef.line) else: - cls_module = cls.fullname.rsplit(".", 1)[0] - if cls_module == builder.current_module: - base = builder.load_global_str(cls.name, cdef.line) + # The base may be a nested class such as "mod.Outer.Inner". + attrs = cls.fullname[len(cls.module_name) + 1 :].split(".") + if cls.module_name == builder.current_module: + base = builder.load_global_str(attrs[0], cdef.line) else: - base = builder.load_module_attr_by_fullname(cls.fullname, cdef.line) + # The module may not have been imported yet, for example if the base class + # was imported through a re-export, or if the module is only imported in + # a function body, so import it if needed. + base = builder.get_module_attr(cls.module_name, attrs[0], cdef.line) + for attr in attrs[1:]: + base = builder.py_get_attr(base, attr, cdef.line) bases.append(base) if cls.fullname in MAGIC_TYPED_DICT_CLASSES: # The remaining base classes are synthesized by mypy and should be ignored. diff --git a/mypyc/test-data/run-classes.test b/mypyc/test-data/run-classes.test index e7ccfa75d02ae..edcd8a4488aea 100644 --- a/mypyc/test-data/run-classes.test +++ b/mypyc/test-data/run-classes.test @@ -1593,11 +1593,15 @@ def test_raise_non_native_exception_subclass_2() -> None: assert False assert x -[case testSubclassUnknownPythonBase] -# The base class is unknown during compilation, so it has type Any +[case testSubclassExternalPythonBase] +# Subclass Python classes defined outside the compiled module (some are unknown during +# compilation and have type Any) +import ctypes from mypy_extensions import mypyc_attr from typing import Any, Generic, TypeVar from unchecked import Base, MetaBase, SecondBase, StrBase # type: ignore +import pkg +from pkg import FunctionImportedBase, Outer, ReExportedBase, StrEnum T = TypeVar("T") @@ -1724,6 +1728,49 @@ def test_generic_bases() -> None: assert KnownGenericBase.__orig_bases__ == (Base, KnownGeneric[int]) assert KnownGenericBase(7).y == 7 +# The bases are imported through re-exports (from modules other than where they are defined) +class ReExportedStrEnum(StrEnum): + value = "testing-value" + +@mypyc_attr(native_class=False) +class FromReExport(ReExportedBase): + pass + +@mypyc_attr(native_class=False) +class FromReExportedError(pkg.Error, ValueError): + pass + +# ctypes.Structure is defined in _ctypes +class CtypesStructure(ctypes.Structure): + pass + +def import_in_function() -> None: + # This doesn't run before the class below is created + import pkg.function_imported + +@mypyc_attr(native_class=False) +class FromFunctionImportedModule(FunctionImportedBase): + pass + +@mypyc_attr(native_class=False) +class FromNested(Outer.Inner): + pass + +@mypyc_attr(native_class=False) +class FromNestedViaModule(pkg.Outer.Inner): + pass + +def test_re_exported_base() -> None: + assert list(ReExportedStrEnum) == [ReExportedStrEnum.value] + assert ReExportedStrEnum.value == "testing-value" + assert isinstance(FromReExport(), ReExportedBase) + assert isinstance(FromReExportedError(), pkg.Error) + assert isinstance(CtypesStructure(), ctypes.Structure) + assert isinstance(FromFunctionImportedModule(), FunctionImportedBase) + assert isinstance(FromNested(), Outer.Inner) + assert FromNested().inner() == "inner" + assert isinstance(FromNestedViaModule(), Outer.Inner) + [file unchecked.py] StrBase = str @@ -1748,6 +1795,33 @@ class Base: def marker(self): return "base" +[file pkg/__init__.py] +from pkg.strenum import StrEnum +from pkg.base import ReExportedBase, Error, Outer +from pkg.function_imported import FunctionImportedBase + +[file pkg/strenum.py] +import enum + +class StrEnum(str, enum.Enum): + pass + +[file pkg/base.py] +class ReExportedBase: + pass + +class Error(Exception): + pass + +class Outer: + class Inner: + def inner(self): + return "inner" + +[file pkg/function_imported.py] +class FunctionImportedBase: + pass + [case testSubclassPy] from b import B, V class A(B):