Skip to content

Commit

Permalink
optional_caster::from_python: reset value on None (fixes #747) (#748)
Browse files Browse the repository at this point in the history
  • Loading branch information
wojdyr authored Oct 5, 2024
1 parent bff96e2 commit 2d1723c
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 2 deletions.
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

0 comments on commit 2d1723c

Please sign in to comment.