From 7c4ac91d75c60e252050e6c52a289b9b656c0a59 Mon Sep 17 00:00:00 2001 From: Michael Carlstrom Date: Sat, 15 Jun 2024 09:25:43 -0400 Subject: [PATCH] Add type[T] support to typing.h (#5166) * add type[T] * style: pre-commit fixes * fix merge --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- include/pybind11/typing.h | 10 ++++++++++ tests/test_pytypes.cpp | 1 + tests/test_pytypes.py | 4 ++++ 3 files changed, 15 insertions(+) diff --git a/include/pybind11/typing.h b/include/pybind11/typing.h index 2c9eaffb..e0d0e45c 100644 --- a/include/pybind11/typing.h +++ b/include/pybind11/typing.h @@ -63,6 +63,11 @@ class Callable : public function { using function::function; }; +template +class Type : public type { + using type::type; +}; + template class Union : public object { using object::object; @@ -131,6 +136,11 @@ struct handle_type_name> { + const_name("], ") + make_caster::name + const_name("]"); }; +template +struct handle_type_name> { + static constexpr auto name = const_name("type[") + make_caster::name + const_name("]"); +}; + template struct handle_type_name> { static constexpr auto name = const_name("Union[") diff --git a/tests/test_pytypes.cpp b/tests/test_pytypes.cpp index e97dceee..e5a318ad 100644 --- a/tests/test_pytypes.cpp +++ b/tests/test_pytypes.cpp @@ -844,6 +844,7 @@ TEST_SUBMODULE(pytypes, m) { m.def("annotate_iterator_int", [](const py::typing::Iterator &) {}); m.def("annotate_fn", [](const py::typing::Callable, py::str)> &) {}); + m.def("annotate_type", [](const py::typing::Type &) {}); m.def("annotate_union", [](py::typing::List> l, diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index ca2c51c4..72dac13b 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -957,6 +957,10 @@ def test_fn_annotations(doc): ) +def test_type_annotation(doc): + assert doc(m.annotate_type) == "annotate_type(arg0: type[int]) -> None" + + def test_union_annotations(doc): assert ( doc(m.annotate_union)