Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/advanced/classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1232,3 +1232,17 @@ appropriate derived-class pointer (e.g. using
more complete example, including a demonstration of how to provide
automatic downcasting for an entire class hierarchy without
writing one get() function for each class.

Accessing the type object
=========================

You can get the type object from a C++ class that has already been registered using:

.. code-block:: python

py::type T_py = py::type::of<T>();

You can directly use ``py::type::of(ob)`` to get the type object from any python
object, just like ``type(ob)`` in Python.
Comment thread
EricCousineau-TRI marked this conversation as resolved.

.. versionadded:: 2.6
12 changes: 12 additions & 0 deletions include/pybind11/cast.h
Original file line number Diff line number Diff line change
Expand Up @@ -2204,6 +2204,18 @@ object object_api<Derived>::call(Args &&...args) const {

PYBIND11_NAMESPACE_END(detail)


template<typename T>
type type::of() {
static_assert(
Comment thread
henryiii marked this conversation as resolved.
std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
"py::type::of<T> only supports the case where T is a registered C++ types."
);

return type((PyObject*) detail::get_type_handle(typeid(T), true).ptr(), borrowed_t());
Comment thread
YannickJadoul marked this conversation as resolved.
}


#define PYBIND11_MAKE_OPAQUE(...) \
namespace pybind11 { namespace detail { \
template<> class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { }; \
Expand Down
16 changes: 16 additions & 0 deletions include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
/* A few forward declarations */
class handle; class object;
class str; class iterator;
class type;
struct arg; struct arg_v;

PYBIND11_NAMESPACE_BEGIN(detail)
Expand Down Expand Up @@ -890,6 +891,21 @@ class iterator : public object {
object value = {};
};



class type : public object {
public:
PYBIND11_OBJECT_COMMON(type, object, PyType_Check)

explicit type(handle h): type((PyObject*) Py_TYPE(h.ptr()), borrowed_t{}) {}
explicit type(object ob): type((PyObject*) Py_TYPE(ob.ptr()), borrowed_t{}) {}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't necessary, I think? object should be a subclass of handle, and there's no extra refcounting going on?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, yes, some slicing, since it's not by reference. But there are precedents for that, I think?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you/we choose to keep the object overload, better to make it a const object &, then. It avoids an unnecessary refcount.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, no, PYBIND11_OBJECT already adds that overload.

#define PYBIND11_OBJECT(Name, Parent, CheckFun) \
PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
/* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
Name(const object &o) : Parent(o) { } \
Name(object &&o) : Parent(std::move(o)) { }

How do we fix this such that it works in the intended way? When do we want py::type(...) to "cast" a py::object to a subclass, and when do we want it to actually call type(...)? Does this mean that @henryiii's original py::type::of is necessary, and that we can't have the py::type(obj) interface I've been dreaming of? :-(

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We use PYBIND11_OBJECT_COMMON instead of PYBIND11_OBJECT.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(I'll try dropping this overload soon)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be a const handle &?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We use PYBIND11_OBJECT_COMMON instead of PYBIND11_OBJECT.

🤦 How did I miss that?

Can this be a const handle &?

Probably, but I don't think it's necessary. handle really is a fancy and more beautiful way of writing PyObject *.


/// Convert C++ type to py::type if previously registered. Does not convert
//standard types, like int, float. etc. yet.
Comment thread
henryiii marked this conversation as resolved.
Outdated
template<typename T>
static type of();
};

class iterable : public object {
public:
PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)
Expand Down
17 changes: 17 additions & 0 deletions tests/test_class.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,23 @@ TEST_SUBMODULE(class_, m) {
);
});

struct Invalid {};

// test_type
m.def("check_type", [](int category) {
// Currently not supported (via a fail at compile time)
// if (category == 2)
Comment thread
henryiii marked this conversation as resolved.
// return py::type::of<int>();
if (category == 1)
return py::type::of<DerivedClass1>();
else
Comment thread
henryiii marked this conversation as resolved.
return py::type::of<Invalid>();
});

m.def("get_type", [](py::object ob) {
return py::type(ob);
});

// test_mismatched_holder
struct MismatchBase1 { };
struct MismatchDerived1 : MismatchBase1 { };
Expand Down
23 changes: 23 additions & 0 deletions tests/test_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,29 @@ def test_instance(msg):
assert cstats.alive() == 0


def test_type():
assert m.check_type(1) == m.DerivedClass1
with pytest.raises(RuntimeError) as execinfo:
m.check_type(0)

assert 'pybind11::detail::get_type_info: unable to find type info' in str(execinfo.value)
assert 'Invalid' in str(execinfo.value)

# Currently not supported
# assert m.check_type(2) == int
Comment thread
henryiii marked this conversation as resolved.


def test_type_py():
assert m.get_type(1) == int
assert m.get_type(m.DerivedClass1()) == m.DerivedClass1
assert m.get_type(int) == type


def test_type_py_nodelete():
# If the above test deleted the class, this will segfault
assert m.get_type(m.DerivedClass1()) == m.DerivedClass1


def test_docstrings(doc):
assert doc(UserType) == "A `py::class_` type for testing"
assert UserType.__name__ == "UserType"
Expand Down