Skip to content

Commit 623bef9

Browse files
authored
[mypyc] Fix undeclared module in C when base class is a re-export (#22357)
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.
1 parent f0eb638 commit 623bef9

2 files changed

Lines changed: 86 additions & 6 deletions

File tree

‎mypyc/irbuild/classdef.py‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -667,11 +667,17 @@ def populate_non_ext_bases(
667667
name = "_NamedTuple"
668668
base = builder.get_module_attr("typing", name, cdef.line)
669669
else:
670-
cls_module = cls.fullname.rsplit(".", 1)[0]
671-
if cls_module == builder.current_module:
672-
base = builder.load_global_str(cls.name, cdef.line)
670+
# The base may be a nested class such as "mod.Outer.Inner".
671+
attrs = cls.fullname[len(cls.module_name) + 1 :].split(".")
672+
if cls.module_name == builder.current_module:
673+
base = builder.load_global_str(attrs[0], cdef.line)
673674
else:
674-
base = builder.load_module_attr_by_fullname(cls.fullname, cdef.line)
675+
# The module may not have been imported yet, for example if the base class
676+
# was imported through a re-export, or if the module is only imported in
677+
# a function body, so import it if needed.
678+
base = builder.get_module_attr(cls.module_name, attrs[0], cdef.line)
679+
for attr in attrs[1:]:
680+
base = builder.py_get_attr(base, attr, cdef.line)
675681
bases.append(base)
676682
if cls.fullname in MAGIC_TYPED_DICT_CLASSES:
677683
# The remaining base classes are synthesized by mypy and should be ignored.

‎mypyc/test-data/run-classes.test‎

Lines changed: 76 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1593,11 +1593,15 @@ def test_raise_non_native_exception_subclass_2() -> None:
15931593
assert False
15941594
assert x
15951595

1596-
[case testSubclassUnknownPythonBase]
1597-
# The base class is unknown during compilation, so it has type Any
1596+
[case testSubclassExternalPythonBase]
1597+
# Subclass Python classes defined outside the compiled module (some are unknown during
1598+
# compilation and have type Any)
1599+
import ctypes
15981600
from mypy_extensions import mypyc_attr
15991601
from typing import Any, Generic, TypeVar
16001602
from unchecked import Base, MetaBase, SecondBase, StrBase # type: ignore
1603+
import pkg
1604+
from pkg import FunctionImportedBase, Outer, ReExportedBase, StrEnum
16011605

16021606
T = TypeVar("T")
16031607

@@ -1724,6 +1728,49 @@ def test_generic_bases() -> None:
17241728
assert KnownGenericBase.__orig_bases__ == (Base, KnownGeneric[int])
17251729
assert KnownGenericBase(7).y == 7
17261730

1731+
# The bases are imported through re-exports (from modules other than where they are defined)
1732+
class ReExportedStrEnum(StrEnum):
1733+
value = "testing-value"
1734+
1735+
@mypyc_attr(native_class=False)
1736+
class FromReExport(ReExportedBase):
1737+
pass
1738+
1739+
@mypyc_attr(native_class=False)
1740+
class FromReExportedError(pkg.Error, ValueError):
1741+
pass
1742+
1743+
# ctypes.Structure is defined in _ctypes
1744+
class CtypesStructure(ctypes.Structure):
1745+
pass
1746+
1747+
def import_in_function() -> None:
1748+
# This doesn't run before the class below is created
1749+
import pkg.function_imported
1750+
1751+
@mypyc_attr(native_class=False)
1752+
class FromFunctionImportedModule(FunctionImportedBase):
1753+
pass
1754+
1755+
@mypyc_attr(native_class=False)
1756+
class FromNested(Outer.Inner):
1757+
pass
1758+
1759+
@mypyc_attr(native_class=False)
1760+
class FromNestedViaModule(pkg.Outer.Inner):
1761+
pass
1762+
1763+
def test_re_exported_base() -> None:
1764+
assert list(ReExportedStrEnum) == [ReExportedStrEnum.value]
1765+
assert ReExportedStrEnum.value == "testing-value"
1766+
assert isinstance(FromReExport(), ReExportedBase)
1767+
assert isinstance(FromReExportedError(), pkg.Error)
1768+
assert isinstance(CtypesStructure(), ctypes.Structure)
1769+
assert isinstance(FromFunctionImportedModule(), FunctionImportedBase)
1770+
assert isinstance(FromNested(), Outer.Inner)
1771+
assert FromNested().inner() == "inner"
1772+
assert isinstance(FromNestedViaModule(), Outer.Inner)
1773+
17271774
[file unchecked.py]
17281775
StrBase = str
17291776

@@ -1748,6 +1795,33 @@ class Base:
17481795
def marker(self):
17491796
return "base"
17501797

1798+
[file pkg/__init__.py]
1799+
from pkg.strenum import StrEnum
1800+
from pkg.base import ReExportedBase, Error, Outer
1801+
from pkg.function_imported import FunctionImportedBase
1802+
1803+
[file pkg/strenum.py]
1804+
import enum
1805+
1806+
class StrEnum(str, enum.Enum):
1807+
pass
1808+
1809+
[file pkg/base.py]
1810+
class ReExportedBase:
1811+
pass
1812+
1813+
class Error(Exception):
1814+
pass
1815+
1816+
class Outer:
1817+
class Inner:
1818+
def inner(self):
1819+
return "inner"
1820+
1821+
[file pkg/function_imported.py]
1822+
class FunctionImportedBase:
1823+
pass
1824+
17511825
[case testSubclassPy]
17521826
from b import B, V
17531827
class A(B):

0 commit comments

Comments
 (0)