pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

Should `PyType` have `module()` method similar to `name()` method?

Open JohnScience opened this issue 2 years ago • 3 comments

I have some code that relies on the type of the object represented PyAny. I'd like to have a test that confirms that the datatype of the python object is <class '<module>.<name>'>.

That's how it looks like right now:

Python::with_gil(|py| {
            let obj = /**/;
            let ty = obj.get_type();
            let ty_name = ty.name().unwrap();
            let ty_module = ty
                .getattr("__module__")
                .unwrap()
                .extract::<String>()
                .unwrap();
            // <class '<module>.<name>'>
            assert!(ty_module == "...");
            assert!(ty_name == "...");
        });
        ```

JohnScience avatar Jun 27 '23 02:06 JohnScience

I think the question here is whether there is some unsafe FFI that we can call to do this. If not, we would just do .getattr("__module__") ourselves and we generally only do that as a fallback when using the stable API or to implement our infrastructure traits like FromPyObject.

adamreichold avatar Jun 27 '23 06:06 adamreichold

So in this case, I suspect we add the method and call PyType_GetModule with a signature like fn module(&self) -> Result<&PyModule, PyTypeError>?

adamreichold avatar Jun 27 '23 06:06 adamreichold

It's worth experimenting with; from the documentation I think this might only work on types called with PyType_FromModuleAndSpec (which doesn't include PyO3 types yet). So we might need to use .getattr("__module__") as a fallback.

davidhewitt avatar Jun 27 '23 06:06 davidhewitt