Skip to content

Commit 4bd538a

Browse files
feat(types): add support for Typing.Callable Special Case (#5202)
* Add special case * linty
1 parent 2e35470 commit 4bd538a

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

include/pybind11/typing.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,14 @@ struct handle_type_name<typing::Callable<Return(Args...)>> {
177177
+ const_name("], ") + make_caster<retval_type>::name + const_name("]");
178178
};
179179

180+
template <typename Return>
181+
struct handle_type_name<typing::Callable<Return(ellipsis)>> {
182+
// PEP 484 specifies this syntax for defining only return types of callables
183+
using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;
184+
static constexpr auto name
185+
= const_name("Callable[..., ") + make_caster<retval_type>::name + const_name("]");
186+
};
187+
180188
template <typename T>
181189
struct handle_type_name<typing::Type<T>> {
182190
static constexpr auto name = const_name("type[") + make_caster<T>::name + const_name("]");

tests/test_pytypes.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -865,6 +865,7 @@ TEST_SUBMODULE(pytypes, m) {
865865
m.def("annotate_fn",
866866
[](const py::typing::Callable<int(py::typing::List<py::str>, py::str)> &) {});
867867

868+
m.def("annotate_fn_only_return", [](const py::typing::Callable<int(py::ellipsis)> &) {});
868869
m.def("annotate_type", [](const py::typing::Type<int> &t) -> py::type { return t; });
869870

870871
m.def("annotate_union",

tests/test_pytypes.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -959,6 +959,13 @@ def test_fn_annotations(doc):
959959
)
960960

961961

962+
def test_fn_return_only(doc):
963+
assert (
964+
doc(m.annotate_fn_only_return)
965+
== "annotate_fn_only_return(arg0: Callable[..., int]) -> None"
966+
)
967+
968+
962969
def test_type_annotation(doc):
963970
assert doc(m.annotate_type) == "annotate_type(arg0: type[int]) -> type"
964971

0 commit comments

Comments
 (0)