feat(types): adds support for TypeGuard and TypeIs (#5194)

* Adds support for TypeGuard and TypeIs

* style: pre-commit fixes

---------

Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Michael Carlstrom 2024-06-25 22:53:15 -04:00 committed by GitHub
parent b5ec7c7174
commit 2be85c6041
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 40 additions and 0 deletions

View File

@ -80,6 +80,16 @@ class Optional : public object {
using object::object;
};
template <typename T>
class TypeGuard : public bool_ {
using bool_::bool_;
};
template <typename T>
class TypeIs : public bool_ {
using bool_::bool_;
};
class NoReturn : public none {
using none::none;
};
@ -87,6 +97,7 @@ class NoReturn : public none {
class Never : public none {
using none::none;
};
#if defined(__cpp_nontype_template_parameter_class)
template <size_t N>
struct StringLiteral {
@ -183,6 +194,16 @@ struct handle_type_name<typing::Optional<T>> {
static constexpr auto name = const_name("Optional[") + make_caster<T>::name + const_name("]");
};
template <typename T>
struct handle_type_name<typing::TypeGuard<T>> {
static constexpr auto name = const_name("TypeGuard[") + make_caster<T>::name + const_name("]");
};
template <typename T>
struct handle_type_name<typing::TypeIs<T>> {
static constexpr auto name = const_name("TypeIs[") + make_caster<T>::name + const_name("]");
};
template <>
struct handle_type_name<typing::NoReturn> {
static constexpr auto name = const_name("NoReturn");
@ -192,6 +213,7 @@ template <>
struct handle_type_name<typing::Never> {
static constexpr auto name = const_name("Never");
};
#if defined(__cpp_nontype_template_parameter_class)
template <typing::StringLiteral... Literals>
struct handle_type_name<typing::Literal<Literals...>> {

View File

@ -892,8 +892,15 @@ TEST_SUBMODULE(pytypes, m) {
return list;
});
m.def("annotate_type_guard", [](py::object &o) -> py::typing::TypeGuard<py::str> {
return py::isinstance<py::str>(o);
});
m.def("annotate_type_is",
[](py::object &o) -> py::typing::TypeIs<py::str> { return py::isinstance<py::str>(o); });
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<int> &o) -> py::object { return o; });

View File

@ -991,6 +991,17 @@ def test_optional_annotations(doc):
)
def test_type_guard_annotations(doc):
assert (
doc(m.annotate_type_guard)
== "annotate_type_guard(arg0: object) -> TypeGuard[str]"
)
def test_type_is_annotations(doc):
assert doc(m.annotate_type_is) == "annotate_type_is(arg0: object) -> TypeIs[str]"
def test_no_return_annotation(doc):
assert doc(m.annotate_no_return) == "annotate_no_return() -> NoReturn"