Skip to content

Commit

Permalink
feat(types): adds support for Never and NoReturn from python Typing (…
Browse files Browse the repository at this point in the history
…#5193)

* Adds support for Never and NoReturn

* lint
  • Loading branch information
InvincibleRMC authored Jun 26, 2024
1 parent 183059f commit 26281c7
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
16 changes: 16 additions & 0 deletions include/pybind11/typing.h
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ class Optional : public object {
using object::object;
};

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

class Never : public none {
using none::none;
};
#if defined(__cpp_nontype_template_parameter_class)
template <size_t N>
struct StringLiteral {
Expand Down Expand Up @@ -176,6 +183,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");
};
#if defined(__cpp_nontype_template_parameter_class)
template <typing::StringLiteral... Literals>
struct handle_type_name<typing::Literal<Literals...>> {
Expand Down
3 changes: 3 additions & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -891,6 +891,9 @@ 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; });
m.def("annotate_optional_to_object",
[](py::typing::Optional<int> &o) -> py::object { return o; });

Expand Down
8 changes: 8 additions & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -991,6 +991,14 @@ def test_optional_annotations(doc):
)


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"


def test_optional_object_annotations(doc):
assert (
doc(m.annotate_optional_to_object)
Expand Down

0 comments on commit 26281c7

Please sign in to comment.