From 523f46fe279e16f4e37f040976b6f8c1eef14c7d Mon Sep 17 00:00:00 2001 From: Leo Chen Date: Fri, 10 Sep 2021 19:12:00 +0800 Subject: [PATCH] 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 --- paddle/fluid/pybind/imperative.cc | 6 +++++- .../paddle/fluid/tests/unittests/test_imperative_basic.py | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/paddle/fluid/pybind/imperative.cc b/paddle/fluid/pybind/imperative.cc index 422d6de6f33..8e230a6a108 100644 --- a/paddle/fluid/pybind/imperative.cc +++ b/paddle/fluid/pybind/imperative.cc @@ -1791,7 +1791,11 @@ void BindImperative(py::module *m_ptr) { .def_property_readonly("type", &imperative::VarBase::Type) .def_property_readonly("dtype", &imperative::VarBase::DataType); - py::class_ layer(m, "Layer"); + // NOTE(zhiqiu): set the metaclass of Layer. + // See details: https://github.com/pybind/pybind11/pull/679 + // https://github.com/pybind/pybind11/blob/028812ae7eee307dca5f8f69d467af7b92cc41c8/tests/test_methods_and_attributes.cpp#L284 + py::class_ layer( + m, "Layer", py::metaclass((PyObject *)&PyType_Type)); // NOLINT layer.def(py::init<>()) .def("forward", [](imperative::Layer &self, diff --git a/python/paddle/fluid/tests/unittests/test_imperative_basic.py b/python/paddle/fluid/tests/unittests/test_imperative_basic.py index 3aed1af5979..3a1ff82290e 100644 --- a/python/paddle/fluid/tests/unittests/test_imperative_basic.py +++ b/python/paddle/fluid/tests/unittests/test_imperative_basic.py @@ -841,6 +841,14 @@ class TestDygraphGuardWithError(unittest.TestCase): y = fluid.layers.matmul(x, x) +class TestMetaclass(unittest.TestCase): + def test_metaclass(self): + self.assertEqual(type(MyLayer).__name__, 'type') + self.assertNotEqual(type(MyLayer).__name__, 'pybind11_type') + self.assertEqual( + type(paddle.fluid.core.VarBase).__name__, 'pybind11_type') + + if __name__ == '__main__': paddle.enable_static() unittest.main() -- GitLab