From dd0e4a0b89beeefeabb10702210030832f4fa5b3 Mon Sep 17 00:00:00 2001 From: Michael Carlstrom Date: Wed, 26 Jun 2024 16:34:06 -0400 Subject: [PATCH] feat(types): add support for Typing.Callable Special Case (#5202) * Add special case * linty --- include/pybind11/typing.h | 8 ++++++++ tests/test_pytypes.cpp | 1 + tests/test_pytypes.py | 7 +++++++ 3 files changed, 16 insertions(+) diff --git a/include/pybind11/typing.h b/include/pybind11/typing.h index cf70b739e..1442cdc7f 100644 --- a/include/pybind11/typing.h +++ b/include/pybind11/typing.h @@ -177,6 +177,14 @@ struct handle_type_name> { + const_name("], ") + make_caster::name + const_name("]"); }; +template +struct handle_type_name> { + // PEP 484 specifies this syntax for defining only return types of callables + using retval_type = conditional_t::value, void_type, Return>; + static constexpr auto name + = const_name("Callable[..., ") + make_caster::name + const_name("]"); +}; + template struct handle_type_name> { static constexpr auto name = const_name("type[") + make_caster::name + const_name("]"); diff --git a/tests/test_pytypes.cpp b/tests/test_pytypes.cpp index 6b347894b..7c30978ce 100644 --- a/tests/test_pytypes.cpp +++ b/tests/test_pytypes.cpp @@ -865,6 +865,7 @@ TEST_SUBMODULE(pytypes, m) { m.def("annotate_fn", [](const py::typing::Callable, py::str)> &) {}); + m.def("annotate_fn_only_return", [](const py::typing::Callable &) {}); m.def("annotate_type", [](const py::typing::Type &t) -> py::type { return t; }); m.def("annotate_union", diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index 92a3a36bf..30931e0b9 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -959,6 +959,13 @@ def test_fn_annotations(doc): ) +def test_fn_return_only(doc): + assert ( + doc(m.annotate_fn_only_return) + == "annotate_fn_only_return(arg0: Callable[..., int]) -> None" + ) + + def test_type_annotation(doc): assert doc(m.annotate_type) == "annotate_type(arg0: type[int]) -> type"