Reputation: 556
I want to write a library for python. As my practice, I tried the code in document.
Cargo.toml
[package]
name = "example"
version = "0.1.0"
authors = ["Yudai Hayashi"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "example"
crate-type = ["cdylib"]
[dependencies]
[dependencies.pyo3]
version = "*"
features = ["extension-module"]
src/lib.rs
#![feature(proc_macro, specialization)]
extern crate pyo3;
use pyo3::{py, PyResult, Python, PyModule};
use pyo3::py::modinit as pymodinit;
// add bindings to the generated python module
// N.B: names: "librust2py" must be the name of the `.so` or `.pyd` file
/// This module is implemented in Rust.
#[pymodinit(rust2py)]
fn init_mod(py: Python, m: &PyModule) -> PyResult<()> {
#[pyfn(m, "sum_as_string")]
// pyo3 aware function. All of our python interface could be declared in a separate module.
// Note that the `#[pyfn()]` annotation automatically converts the arguments from
// Python objects to Rust values; and the Rust return value back into a Python object.
fn sum_as_string_py(_: Python, a:i64, b:i64) -> PyResult<String> {
let out = sum_as_string(a, b);
Ok(out)
}
Ok(())
}
// logic implemented as a normal Rust function
fn sum_as_string(a:i64, b:i64) -> String {
format!("{}", a + b).to_string()
}
When I build this program, I got some errors.
error[E0432]: unresolved import `pyo3::py`
--> src/lib.rs:4:12
|
4 | use pyo3::{py, PyResult, Python, PyModule};
| ^^
| |
| no `py` in the root
| help: a similar name exists in the module: `Py`
error[E0432]: unresolved import `pyo3::py`
--> src/lib.rs:6:11
|
6 | use pyo3::py::modinit as pymodinit;
| ^^ could not find `py` in `pyo3`
error: cannot determine resolution for the attribute macro `pymodinit`
--> src/lib.rs:11:3
|
11 | #[pymodinit(rust2py)]
| ^^^^^^^^^
|
= note: import resolution is stuck, try simplifying macro imports
error: cannot find attribute macro `pyfn` in this scope
--> src/lib.rs:14:7
|
14 | #[pyfn(m, "sum_as_string")]
| ^^^^
error: aborting due to 4 previous errors
For more information about this error, try `rustc --explain E0432`.
error: Could not compile `example`.
This error message says that there is no "py" in pyo3 module. I looked for this error message, but I cannot find similar errors.
How to deal with this issue?
Upvotes: 3
Views: 617
Reputation: 19662
There is no mod
called py
in the latest version of pyo3
. You've landed on documentation or examples related to an old version of the library. The last version that had this mod
was 0.2.7.
If you have no interest other than running the code, set the version you require of pyo3
in your Cargo.toml
dependencies to 0.2.7
and it should compile out of the box (a cursory glance confirms that all symbols seem to exist in that version).
If you want to actually investigate the newer version, the new documentation has up to date examples.
Upvotes: 4