Skip to content

Commit 5379b53

Browse files
committed
nanobind: fix adapted ctor stub signature (remoe redundant self)
1 parent 5a80d34 commit 5379b53

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/litgen/internal/adapted_types/adapted_function.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1207,7 +1207,15 @@ def _stub_params_list_signature(self) -> list[str]:
12071207
cpp_adapted_function_terse = self.cpp_adapted_function.with_terse_types()
12081208
cpp_parameters = cpp_adapted_function_terse.parameter_list.parameters
12091209
r = []
1210-
for param in cpp_parameters:
1210+
for i, param in enumerate(cpp_parameters):
1211+
# For nanobind, skip first "self" argument in constructors
1212+
is_nanobind = self.options.bind_library == BindLibraryType.nanobind
1213+
if is_nanobind:
1214+
is_ctor = self.is_constructor()
1215+
is_first_self_arg = i == 0 and param.decl.decl_name == "self"
1216+
if is_ctor and is_first_self_arg:
1217+
continue
1218+
12111219
param_decl = param.decl
12121220

12131221
param_name_python = cpp_to_python.var_name_to_python(self.options, param_decl.decl_name)

src/litgen/tests/internal/adapted_types/adapted_class_test.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -751,6 +751,34 @@ def test_numeric_array_member() -> None:
751751
)
752752

753753

754+
def test_nanobind_adapted_ctor_stub() -> None:
755+
# The constructor params below will automatically be "adapted" into std::array<uint8_t, 4>
756+
code = """
757+
struct Color4
758+
{
759+
Color4(const uint8_t _rgba[4]);
760+
uint8_t rgba[4];
761+
};
762+
"""
763+
options = litgen.LitgenOptions()
764+
options.bind_library = BindLibraryType.nanobind
765+
generated_code = litgen.generate_code(options, code)
766+
767+
# Below, we test that the ctor signature is adapted to accept List[int]
768+
# (and does not specify an additional self parameter, cf AdaptedFunction.stub_params_list_signature())
769+
# print(generated_code.stub_code)
770+
code_utils.assert_are_codes_equal(
771+
generated_code.stub_code,
772+
"""
773+
class Color4:
774+
def __init__(self, _rgba: List[int]) -> None:
775+
pass
776+
rgba: np.ndarray # ndarray[type=uint8_t, size=4]
777+
"""
778+
)
779+
780+
781+
754782
def test_adapted_ctor() -> None:
755783
# The constructor for Color4 will be adapted to accept std::array<uint8_t, 4>
756784
code = """

0 commit comments

Comments
 (0)