feat(types): add support for Typing.Callable Special Case (#5202)

* Add special case

* linty
This commit is contained in:
Michael Carlstrom 2024-06-26 16:34:06 -04:00 committed by Henry Schreiner
parent 3b47b4648b
commit dd0e4a0b89
3 changed files with 16 additions and 0 deletions

View File

@ -177,6 +177,14 @@ struct handle_type_name<typing::Callable<Return(Args...)>> {
+ const_name("], ") + make_caster<retval_type>::name + const_name("]"); + const_name("], ") + make_caster<retval_type>::name + const_name("]");
}; };
template <typename Return>
struct handle_type_name<typing::Callable<Return(ellipsis)>> {
// PEP 484 specifies this syntax for defining only return types of callables
using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;
static constexpr auto name
= const_name("Callable[..., ") + make_caster<retval_type>::name + const_name("]");
};
template <typename T> template <typename T>
struct handle_type_name<typing::Type<T>> { struct handle_type_name<typing::Type<T>> {
static constexpr auto name = const_name("type[") + make_caster<T>::name + const_name("]"); static constexpr auto name = const_name("type[") + make_caster<T>::name + const_name("]");

View File

@ -865,6 +865,7 @@ TEST_SUBMODULE(pytypes, m) {
m.def("annotate_fn", m.def("annotate_fn",
[](const py::typing::Callable<int(py::typing::List<py::str>, py::str)> &) {}); [](const py::typing::Callable<int(py::typing::List<py::str>, py::str)> &) {});
m.def("annotate_fn_only_return", [](const py::typing::Callable<int(py::ellipsis)> &) {});
m.def("annotate_type", [](const py::typing::Type<int> &t) -> py::type { return t; }); m.def("annotate_type", [](const py::typing::Type<int> &t) -> py::type { return t; });
m.def("annotate_union", m.def("annotate_union",

View File

@ -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): def test_type_annotation(doc):
assert doc(m.annotate_type) == "annotate_type(arg0: type[int]) -> type" assert doc(m.annotate_type) == "annotate_type(arg0: type[int]) -> type"