Python not recognising Pyo3 class

50 Views Asked by At

I am new to rust and I was trying pyo3 today. Following is my naive example:

use pyo3::prelude::*;

#[pyclass]
struct TestClass {
    symbol: i32,
}

#[pymethods]
impl TestClass {
    #[new]
    fn new(symbol: i32) -> PyResult<Self> {
        Ok(TestClass { symbol })
    }

    #[staticmethod]
    fn print_symbol(value: i32) -> PyResult<()> {
        print!("print value passed in: {} \n", value);
        Ok(())
    }
}

/// A Python module implemented in Rust.
#[pymodule]
fn test_pyo3(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<TestClass>()?;
    Ok(())
}

My Cargo.toml looks like this:

[package]
name = "test_pyo3"
version = "0.1.0"
edition = "2021"

# 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 = { version = "0.20.0", features = ["extension-module"] }

In Python I was doing:

from test_pyo3 import TestClass

t = TestClass(23)

t.print_symbol(50)
# output
# print value passed in: 50

In PyCharm, I was trying to check the python implementation (if possible) for the TestClass; however I was getting: Cannot find reference 'TestClass' in __init__.py. I understand that I didn't have a __init__.py file if I were coding in python; however I was expecting pyo3 to generate all this (or at least make available the generated python implementations).

Why python cannot find the reference for TestClass in this case?

0

There are 0 best solutions below