Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add const PyClass instances to a module. #1102

Closed
g-bauer opened this issue Aug 13, 2020 · 1 comment · Fixed by #1124
Closed

Add const PyClass instances to a module. #1102

g-bauer opened this issue Aug 13, 2020 · 1 comment · Fixed by #1124

Comments

@g-bauer
Copy link

g-bauer commented Aug 13, 2020

I am not able to add a const instance of a PyClass to a module. I tried different approaches (see lib.rs below) without success.

Cargo.toml

[package]
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "test_pyo3"
crate-type = ["cdylib"]

[dependencies.pyo3]
git = "https://github.com/PyO3/pyo3"
features = ["extension-module"]

lib.rs

use pyo3::prelude::*;

#[pyclass]
struct Test {}

const T: Test = Test {};

#[pymodule]
fn test_pyo3(py: Python<'_>, m: &PyModule) -> PyResult<()> {
    // original approach
    // the trait `pyo3::conversion::ToPyObject` is not implemented for `Test`
    m.add("T", T)?;
    
    // cannot infer type for type parameter `V` declared on the associated function `add`
    m.add("T", T.into_py(py))?;
    
    // the trait `pyo3::conversion::ToPyObject` is not implemented for `std::result::Result<pyo3::instance::Py<Test>, pyo3::err::PyErr>`  
    m.add("T", Py::new(py, T))?;
    Ok(())
}

Thanks a lot!

@birkenfeld
Copy link
Member

m.add("T", Py::new(py, T)?)?; works for the immediate issue.

On master, the into_py() variant also works. (It creates a Py<PyAny> though, not a Py<Test>.)

Plain T doesn't work in both versions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants