mirror of
https://github.com/pybind/pybind11.git
synced 2024-11-28 16:11:59 +00:00
Added option to add return_name
to custom type_caster
.
This allows to define different python type hints for arguments and return value. This is implemented using template class `as_return_type` in order to check if `return_name` is available in the `type_caster` at compile time. If `return_name` is not available, it falls back to the previous usage of `name` for both args and return value.
This commit is contained in:
parent
8a801bdc32
commit
dd829c5994
@ -101,6 +101,31 @@ inline std::string replace_newlines_and_squash(const char *text) {
|
||||
# define PYBIND11_COMPAT_STRDUP strdup
|
||||
#endif
|
||||
|
||||
/// Type trait checker for `descr`.
|
||||
template<typename>
|
||||
struct is_descr : std::false_type {};
|
||||
|
||||
template<size_t N, typename... Ts>
|
||||
struct is_descr<descr<N, Ts...>> : std::true_type {};
|
||||
|
||||
template<size_t N, typename... Ts>
|
||||
struct is_descr<const descr<N, Ts...>> : std::true_type {};
|
||||
|
||||
/// Checks for `return_name` in `type_caster` to replace `name` for return type hints.
|
||||
/// this is useful for having a different python type hint for args vs return value,
|
||||
/// e.g., `std::filesystem::path` -> Arg: `Union[os.PathLike, str, bytes]`, return: `Path`.
|
||||
template<typename T, typename Enable = void>
|
||||
struct as_return_type
|
||||
{
|
||||
static constexpr auto name = T::name;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct as_return_type<T, typename std::enable_if_t<is_descr<decltype(T::return_name)>::value>>
|
||||
{
|
||||
static constexpr auto name = T::return_name;
|
||||
};
|
||||
|
||||
PYBIND11_NAMESPACE_END(detail)
|
||||
|
||||
/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
|
||||
@ -320,7 +345,8 @@ protected:
|
||||
/* Generate a readable signature describing the function's arguments and return
|
||||
value types */
|
||||
static constexpr auto signature
|
||||
= const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name;
|
||||
= const_name("(") + cast_in::arg_names + const_name(") -> ")
|
||||
+ as_return_type<cast_out>::name;
|
||||
PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
|
||||
|
||||
/* Register the function with Python from generic (non-templated) code */
|
||||
|
Loading…
Reference in New Issue
Block a user