如何解决Pyo3:没有为 `&Py<PyAny>` 实现特性 `PyClass`
我正在学习 Rust 并尝试使用 pyo3 和 maturin 制作一个非常简单的 Python 模块。不过,我在 Rust 代码上遇到了问题,
Cargo.toml
[package]
name = "lenrs"
version = "0.1.0"
authors = ["matheusfillipe"]
edition = "2018"
[dependencies.pyo3]
version = "0.13.2"
features = ["extension-module"]
[lib]
crate-type = ["cdylib"]
name = "lenrs"
src/lib.rs
extern crate pyo3;
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
#[pyfunction]
fn length(py: Python,obj: &PyObject) -> PyResult<PyObject> {
if let Ok(s) = obj.extract::<String>(py) {
return Ok(s.len().to_object(py));
}
if let Ok(s) = obj.extract::<Vec<String>>(py) {
return Ok(s.len().to_object(py));
}
Err(PyTypeError::new_err("Not Supported"))
}
#[pymodule]
fn lenrs(py: Python,m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(length))?;
Ok(())
}
lenrs/init.py
from .lenrs import *
构建输出
$ cargo build
Compiling lenrs v0.1.0 (/home/matheus/projects/learn-rust/lenrs)
error[E0277]: the trait bound `&Py<PyAny>: PyClass` is not satisfied
--> src/lib.rs:7:1
|
7 | #[pyfunction]
| ^^^^^^^^^^^^^ the trait `PyClass` is not implemented for `&Py<PyAny>`
|
= note: required because of the requirements on the impl of `pyo3::FromPyObject<'_>` for `&Py<PyAny>`
= note: required because of the requirements on the impl of `ExtractExt<'_>` for `&Py<PyAny>`
= note: this error originates in an attribute macro (in Nightly builds,run with -Z macro-backtrace for more info)
error: aborting due to prevIoUs error
For more information about this error,try `rustc --explain E0277`.
error: Could not compile `lenrs`
To learn more,run the command again with --verbose.
我发现问题出在 #[pyfunction]
上。当我有一个只适用于字符串的更简单的版本并且 length
函数将返回 PyResult<()>
时,一切都运行良好,最后我只会返回 Ok(())
但现在我不是真的如果类型不受支持,确定如何使此函数引发 python 错误。
解决方法
我刚刚发现 obj 不应该是引用,将函数签名更改为:<Display(Name:="Date")>
<DisplayFormat(DataFormatString:="{0:yyyy-MM-dd}",ApplyFormatInEditMode:=True)>
<DataType(DataType.Date)>
Public Property EventDate As DateTime
<Display(Name:="Start Time")>
<DisplayFormat(DataFormatString:="{0:hh:mm:ss}",ApplyFormatInEditMode:=True)>
<DataType(DataType.Time)>
Public Property StartTime As DateTime?
使其工作:
fn length(py: Python,obj: PyObject) -> PyResult<PyObject>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。