From 26281c79861ddc96ad8dbdda8fec53cc6252e1a5 Mon Sep 17 00:00:00 2001 From: Michael Carlstrom Date: Tue, 25 Jun 2024 21:10:25 -0400 Subject: [PATCH] feat(types): adds support for Never and NoReturn from python Typing (#5193) * Adds support for Never and NoReturn * lint --- include/pybind11/typing.h | 16 ++++++++++++++++ tests/test_pytypes.cpp | 3 +++ tests/test_pytypes.py | 8 ++++++++ 3 files changed, 27 insertions(+) diff --git a/include/pybind11/typing.h b/include/pybind11/typing.h index fb37f0021..55f1f949d 100644 --- a/include/pybind11/typing.h +++ b/include/pybind11/typing.h @@ -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 struct StringLiteral { @@ -176,6 +183,15 @@ struct handle_type_name> { static constexpr auto name = const_name("Optional[") + make_caster::name + const_name("]"); }; +template <> +struct handle_type_name { + static constexpr auto name = const_name("NoReturn"); +}; + +template <> +struct handle_type_name { + static constexpr auto name = const_name("Never"); +}; #if defined(__cpp_nontype_template_parameter_class) template struct handle_type_name> { diff --git a/tests/test_pytypes.cpp b/tests/test_pytypes.cpp index 952b5af6e..ce6b93326 100644 --- a/tests/test_pytypes.cpp +++ b/tests/test_pytypes.cpp @@ -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 &o) -> py::object { return o; }); diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index b265512c8..923cebaf5 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -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)