11个版本 (5个重大更新)
新 0.6.0 | 2024年8月22日 |
---|---|
0.5.3 | 2024年8月21日 |
0.4.0 | 2024年8月13日 |
0.3.0 | 2024年8月9日 |
0.1.2 | 2024年8月7日 |
#45 在 过程宏 中
每月1,623 次下载
用于 5 个crate(直接使用3个)
67KB
1.5K SLoC
pyo3-stub-gen
为PyO3和maturin项目生成Python stub文件(*.pyi
)的工具。
crate名称 | crates.io | docs.rs | 文档(主文档) |
---|---|---|---|
pyo3-stub-gen | |||
pyo3-stub-gen-derive |
设计
我们的目标是创建一个从Rust代码生成stub文件*.pyi
,然而,由于Rust和Python类型系统之间的差异以及proc-macro的限制,自动完整翻译是不可能的。我们采用半自动方法
- 提供默认翻译器,它将在大多数情况下工作,但不适用于所有情况
- 还提供手动指定翻译的方法。
如果默认翻译器不起作用,用户可以手动指定翻译,这些手动翻译可以与默认翻译器生成的翻译集成。因此,用户尽可能使用默认翻译器,仅针对边缘情况指定翻译。
pyo3-stub-gen crate提供手动指定翻译的方法,而pyo3-stub-gen-derive crate提供基于pyo3-stub-gen机制的默认翻译器作为过程宏。
使用方法
如果您在寻找一个工作示例,请参阅示例目录。
示例 | 描述 |
---|---|
examples/pure | 纯Rust maturin项目的示例 |
examples/mixed | 混合Rust/Python maturin项目的示例 |
examples/mixed_sub | 带子模块的混合Rust/Python maturin项目示例 |
在此,我们基于 pyo3-stub-gen crate的 examples/pure 示例,描述基本用法。
使用proc-macro注释Rust代码
此crate提供了过程宏 #[gen_stub_pyfunction]
和其他宏来生成Python存根文件。它与PyO3的 #[pyfunction]
宏一起使用。让我们考虑一个简单的PyO3项目。
use pyo3::prelude::*;
#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
Ok((a + b).to_string())
}
#[pymodule]
fn your_module_name(m: &Bound<PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
Ok(())
}
要为此项目生成存根文件,请按照以下方式修改它
use pyo3::prelude::*;
use pyo3_stub_gen::{derive::gen_stub_pyfunction, define_stub_info_gatherer};
#[gen_stub_pyfunction] // Proc-macro attribute to register a function to stub file generator.
#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
Ok((a + b).to_string())
}
#[pymodule]
fn your_module_name(m: &Bound<PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
Ok(())
}
// Define a function to gather stub information.
define_stub_info_gatherer!(stub_info);
生成存根文件
然后在 src/bin/stub_gen.rs
中创建一个可执行目标来生成存根文件
use pyo3_stub_gen::Result;
fn main() -> Result<()> {
// `stub_info` is a function defined by `define_stub_info_gatherer!` macro.
let stub = pure::stub_info()?;
stub.generate()?;
Ok(())
}
并在 [lib]
部分的 Cargo.toml
中添加 rlib
,除了 cdylib
[lib]
crate-type = ["cdylib", "rlib"]
此目标在执行时生成存根文件 pure.pyi
cargo run --bin stub_gen
存根文件被 maturin
自动找到,并包含在wheel包中。有关更多详细信息,请参阅 maturin文档。
贡献
待编写。
许可证
© 2024 Jij Inc.
本项目受以下任一许可证的许可
- Apache许可证2.0版本,(LICENSE-APACHE 或 https://apache.ac.cn/licenses/LICENSE-2.0)
- MIT许可证 (LICENSE-MIT 或 https://opensource.org/licenses/MIT)
任选其一。
链接
- pybind11-stubgen
- 基于 pybind11 的C++项目的存根文件生成器。
依赖项
~7–13MB
~153K SLoC