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

feat(types): adds support for Never and NoReturn from python Typing #5193

Merged
merged 3 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
18 changes: 18 additions & 0 deletions include/pybind11/typing.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,14 @@ class Optional : public object {
using object::object;
};

class NoReturn : public none {
using none::none;
};

class Never : public none {
using none::none;
};

PYBIND11_NAMESPACE_END(typing)

PYBIND11_NAMESPACE_BEGIN(detail)
Expand Down Expand Up @@ -153,5 +161,15 @@ struct handle_type_name<typing::Optional<T>> {
static constexpr auto name = const_name("Optional[") + make_caster<T>::name + const_name("]");
};

template <>
struct handle_type_name<typing::NoReturn> {
static constexpr auto name = const_name("NoReturn");
};

template <>
struct handle_type_name<typing::Never> {
static constexpr auto name = const_name("Never");
};

PYBIND11_NAMESPACE_END(detail)
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
3 changes: 3 additions & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -867,4 +867,7 @@ TEST_SUBMODULE(pytypes, m) {
list.append(py::none());
return list;
});

m.def("annotate_no_return", []() -> py::typing::NoReturn { throw 0; });
m.def("annotate_never", []() -> py::typing::Never { throw 0; });
}
8 changes: 8 additions & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,3 +982,11 @@ def test_optional_annotations(doc):
doc(m.annotate_optional)
== "annotate_optional(arg0: list) -> list[Optional[str]]"
)


def test_no_return_annotation(doc):
assert doc(m.annotate_no_return) == "annotate_no_return() -> NoReturn"


def test_never_annotation(doc):
assert doc(m.annotate_never) == "annotate_never() -> Never"