Skip to content

Commit 35f402c

Browse files
authored
Support type stub generation for staticmethod (#14934)
Fixes #13574 This PR fixes the generation of type hints for static methods of pybind11 classes. The code changes are based on the suggestions in #13574. The fix introduces an additional check if the property under inspection is of type `staticmethod`. If it is, the type information is read from the staticmethod's `__func__` attribute, instead of the staticmethod instance itself. I added a test for C++ classes with static methods bound using pybind11. Both, an overloaded and a non-overloaded static method are tested.
1 parent fbb738a commit 35f402c

File tree

4 files changed

+66
-6
lines changed

4 files changed

+66
-6
lines changed

mypy/stubgenc.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -530,12 +530,14 @@ def is_classmethod(self, class_info: ClassInfo, name: str, obj: object) -> bool:
530530
return inspect.ismethod(obj)
531531

532532
def is_staticmethod(self, class_info: ClassInfo | None, name: str, obj: object) -> bool:
533-
if self.is_c_module:
533+
if class_info is None:
534534
return False
535+
elif self.is_c_module:
536+
raw_lookup: Mapping[str, Any] = getattr(class_info.cls, "__dict__") # noqa: B009
537+
raw_value = raw_lookup.get(name, obj)
538+
return isinstance(raw_value, staticmethod)
535539
else:
536-
return class_info is not None and isinstance(
537-
inspect.getattr_static(class_info.cls, name), staticmethod
538-
)
540+
return isinstance(inspect.getattr_static(class_info.cls, name), staticmethod)
539541

540542
@staticmethod
541543
def is_abstract_method(obj: object) -> bool:
@@ -761,7 +763,7 @@ def generate_class_stub(self, class_name: str, cls: type, output: list[str]) ->
761763
The result lines will be appended to 'output'. If necessary, any
762764
required names will be added to 'imports'.
763765
"""
764-
raw_lookup = getattr(cls, "__dict__") # noqa: B009
766+
raw_lookup: Mapping[str, Any] = getattr(cls, "__dict__") # noqa: B009
765767
items = self.get_members(cls)
766768
if self.resort_members:
767769
items = sorted(items, key=lambda x: method_name_sort_key(x[0]))
@@ -793,7 +795,9 @@ def generate_class_stub(self, class_name: str, cls: type, output: list[str]) ->
793795
continue
794796
attr = "__init__"
795797
# FIXME: make this nicer
796-
if self.is_classmethod(class_info, attr, value):
798+
if self.is_staticmethod(class_info, attr, value):
799+
class_info.self_var = ""
800+
elif self.is_classmethod(class_info, attr, value):
797801
class_info.self_var = "cls"
798802
else:
799803
class_info.self_var = "self"

test-data/pybind11_mypy_demo/src/main.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,13 @@ const Point Point::y_axis = Point(0, 1);
118118
Point::LengthUnit Point::length_unit = Point::LengthUnit::mm;
119119
Point::AngleUnit Point::angle_unit = Point::AngleUnit::radian;
120120

121+
struct Foo
122+
{
123+
static int some_static_method(int a, int b) { return a * 42 + b; }
124+
static int overloaded_static_method(int value) { return value * 42; }
125+
static double overloaded_static_method(double value) { return value * 42; }
126+
};
127+
121128
} // namespace: basics
122129

123130
void bind_basics(py::module& basics) {
@@ -166,6 +173,14 @@ void bind_basics(py::module& basics) {
166173
.value("radian", Point::AngleUnit::radian)
167174
.value("degree", Point::AngleUnit::degree);
168175

176+
// Static methods
177+
py::class_<Foo> pyFoo(basics, "Foo");
178+
179+
pyFoo
180+
.def_static("some_static_method", &Foo::some_static_method, R"#(None)#", py::arg("a"), py::arg("b"))
181+
.def_static("overloaded_static_method", py::overload_cast<int>(&Foo::overloaded_static_method), py::arg("value"))
182+
.def_static("overloaded_static_method", py::overload_cast<double>(&Foo::overloaded_static_method), py::arg("value"));
183+
169184
// Module-level attributes
170185
basics.attr("PI") = std::acos(-1);
171186
basics.attr("__version__") = "0.0.1";

test-data/pybind11_mypy_demo/stubgen-include-docs/pybind11_mypy_demo/basics.pyi

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,36 @@ from typing import ClassVar, List, overload
33
PI: float
44
__version__: str
55

6+
class Foo:
7+
def __init__(self, *args, **kwargs) -> None:
8+
"""Initialize self. See help(type(self)) for accurate signature."""
9+
@overload
10+
@staticmethod
11+
def overloaded_static_method(value: int) -> int:
12+
"""overloaded_static_method(*args, **kwargs)
13+
Overloaded function.
14+
15+
1. overloaded_static_method(value: int) -> int
16+
17+
2. overloaded_static_method(value: float) -> float
18+
"""
19+
@overload
20+
@staticmethod
21+
def overloaded_static_method(value: float) -> float:
22+
"""overloaded_static_method(*args, **kwargs)
23+
Overloaded function.
24+
25+
1. overloaded_static_method(value: int) -> int
26+
27+
2. overloaded_static_method(value: float) -> float
28+
"""
29+
@staticmethod
30+
def some_static_method(a: int, b: int) -> int:
31+
"""some_static_method(a: int, b: int) -> int
32+
33+
None
34+
"""
35+
636
class Point:
737
class AngleUnit:
838
__members__: ClassVar[dict] = ... # read-only

test-data/pybind11_mypy_demo/stubgen/pybind11_mypy_demo/basics.pyi

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,17 @@ from typing import ClassVar, List, overload
33
PI: float
44
__version__: str
55

6+
class Foo:
7+
def __init__(self, *args, **kwargs) -> None: ...
8+
@overload
9+
@staticmethod
10+
def overloaded_static_method(value: int) -> int: ...
11+
@overload
12+
@staticmethod
13+
def overloaded_static_method(value: float) -> float: ...
14+
@staticmethod
15+
def some_static_method(a: int, b: int) -> int: ...
16+
617
class Point:
718
class AngleUnit:
819
__members__: ClassVar[dict] = ... # read-only

0 commit comments

Comments
 (0)