File tree Expand file tree Collapse file tree 3 files changed +28
-11
lines changed Expand file tree Collapse file tree 3 files changed +28
-11
lines changed Original file line number Diff line number Diff line change @@ -895,10 +895,9 @@ class iterator : public object {
895
895
896
896
class type : public object {
897
897
public:
898
- PYBIND11_OBJECT_COMMON (type, object, PyType_Check)
898
+ PYBIND11_OBJECT (type, object, PyType_Check)
899
899
900
- explicit type (handle h): type((PyObject*) Py_TYPE(h.ptr()), borrowed_t{}) {}
901
- explicit type (object ob): type((PyObject*) Py_TYPE(ob.ptr()), borrowed_t{}) {}
900
+ static type of (handle h) { return type ((PyObject*) Py_TYPE (h.ptr ()), borrowed_t {}); }
902
901
903
902
// / Convert C++ type to py::type if previously registered. Does not convert
904
903
// standard types, like int, float. etc. yet.
Original file line number Diff line number Diff line change @@ -148,8 +148,16 @@ TEST_SUBMODULE(class_, m) {
148
148
return py::type::of<Invalid>();
149
149
});
150
150
151
- m.def (" get_type" , [](py::object ob) {
152
- return py::type (ob);
151
+ m.def (" get_type_of" , [](py::object ob) {
152
+ return py::type::of (ob);
153
+ });
154
+
155
+ m.def (" as_type" , [](py::object ob) {
156
+ auto tp = py::type (ob);
157
+ if (py::isinstance<py::type>(ob))
158
+ return tp;
159
+ else
160
+ throw std::runtime_error (" Invalid type" );
153
161
});
154
162
155
163
// test_mismatched_holder
Original file line number Diff line number Diff line change @@ -39,15 +39,25 @@ def test_type():
39
39
# assert m.check_type(2) == int
40
40
41
41
42
- def test_type_py ():
43
- assert m .get_type (1 ) == int
44
- assert m .get_type (m .DerivedClass1 ()) == m .DerivedClass1
45
- assert m .get_type (int ) == type
42
+ def test_type_of_py ():
43
+ assert m .get_type_of (1 ) == int
44
+ assert m .get_type_of (m .DerivedClass1 ()) == m .DerivedClass1
45
+ assert m .get_type_of (int ) == type
46
46
47
47
48
- def test_type_py_nodelete ():
48
+ def test_type_of_py_nodelete ():
49
49
# If the above test deleted the class, this will segfault
50
- assert m .get_type (m .DerivedClass1 ()) == m .DerivedClass1
50
+ assert m .get_type_of (m .DerivedClass1 ()) == m .DerivedClass1
51
+
52
+
53
+ def test_as_type_py ():
54
+ assert m .as_type (int ) == int
55
+
56
+ with pytest .raises (RuntimeError ):
57
+ assert m .as_type (1 ) == int
58
+
59
+ with pytest .raises (RuntimeError ):
60
+ assert m .as_type (m .DerivedClass1 ()) == m .DerivedClass1
51
61
52
62
53
63
def test_docstrings (doc ):
You can’t perform that action at this time.
0 commit comments