Skip to content

Commit 523f46f

Browse files
authored
change metaclass of Layer from pybind11_builtins.pybind11_type to type (#35538)
* change metaclass of Layer from pybind11_builtins.pybind11_type to type * fix cast * add ut
1 parent fe4deac commit 523f46f

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

paddle/fluid/pybind/imperative.cc

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1791,7 +1791,11 @@ void BindImperative(py::module *m_ptr) {
17911791
.def_property_readonly("type", &imperative::VarBase::Type)
17921792
.def_property_readonly("dtype", &imperative::VarBase::DataType);
17931793

1794-
py::class_<imperative::Layer, Layer /* <--- trampoline*/> layer(m, "Layer");
1794+
// NOTE(zhiqiu): set the metaclass of Layer.
1795+
// See details: https://github.com/pybind/pybind11/pull/679
1796+
// https://github.com/pybind/pybind11/blob/028812ae7eee307dca5f8f69d467af7b92cc41c8/tests/test_methods_and_attributes.cpp#L284
1797+
py::class_<imperative::Layer, Layer /* <--- trampoline*/> layer(
1798+
m, "Layer", py::metaclass((PyObject *)&PyType_Type)); // NOLINT
17951799
layer.def(py::init<>())
17961800
.def("forward",
17971801
[](imperative::Layer &self,

python/paddle/fluid/tests/unittests/test_imperative_basic.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -841,6 +841,14 @@ def test_without_guard(self):
841841
y = fluid.layers.matmul(x, x)
842842

843843

844+
class TestMetaclass(unittest.TestCase):
845+
def test_metaclass(self):
846+
self.assertEqual(type(MyLayer).__name__, 'type')
847+
self.assertNotEqual(type(MyLayer).__name__, 'pybind11_type')
848+
self.assertEqual(
849+
type(paddle.fluid.core.VarBase).__name__, 'pybind11_type')
850+
851+
844852
if __name__ == '__main__':
845853
paddle.enable_static()
846854
unittest.main()

0 commit comments

Comments
 (0)