Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optional_caster::from_python: reset value on None #748

Merged
merged 1 commit into from
Oct 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions include/nanobind/stl/detail/nb_optional.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ struct optional_caster {
NB_TYPE_CASTER(Optional, optional_name(Caster::Name))

bool from_python(handle src, uint8_t flags, cleanup_list* cleanup) noexcept {
if (src.is_none())
// default-constructed value is already empty
if (src.is_none()) {
value.reset();
return true;
}

Caster caster;
if (!caster.from_python(src, flags_for_local_caster<T>(flags), cleanup) ||
Expand Down
4 changes: 4 additions & 0 deletions tests/test_stl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,10 @@ NB_MODULE(test_stl_ext, m) {
return x;
});

m.def("vector_optional_str", [](const std::vector<std::optional<std::string>>& x) {
return x;
});

m.def("pass_wstr", [](std::wstring ws) { return ws; });

// uncomment to see compiler error:
Expand Down
1 change: 1 addition & 0 deletions tests/test_stl.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,7 @@ def test69_complex_array():
def test70_vec_char():
assert isinstance(t.vector_str("123"), str)
assert isinstance(t.vector_str(["123", "345"]), list)
assert t.vector_optional_str(["abc", None]) == ["abc", None]


def test71_null_input():
Expand Down
2 changes: 2 additions & 0 deletions tests/test_stl_ext.pyi.ref
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,8 @@ def vec_return_copyable() -> list[Copyable]: ...

def vec_return_movable() -> list[Movable]: ...

def vector_optional_str(arg: Sequence[str | None], /) -> list[str | None]: ...

@overload
def vector_str(arg: Sequence[str], /) -> list[str]: ...

Expand Down