Non-throwing cast
#4922
VelocityRa
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I often declare methods/functions that contain arguments with multiple possible types (
Union
/std::variant
), so I often use this pattern, many layers deep and/or with chained checks.Assume the following code is in a
def
func/method lambda:This is more verbose code-wise and presumably duplicates work for no reason.
If there was a non-throwing
py::cast
variant (that returned ie.nullptr
/std::nullopt
on failure) we could just do:but there is none, and throwing exceptions is expensive / not recommended for non-exceptional program logic.
Note: I use a user-defined type
MyType
here (and specifically casting to a pointer), but this should of course also work for pybind11 C++ Python API types likepy::int_
(I suppose it should not cast to a pointer in these cases).Beta Was this translation helpful? Give feedback.
All reactions