Skip to content

Commit

Permalink
Update README
Browse files Browse the repository at this point in the history
  • Loading branch information
termoshtt committed Jan 5, 2024
1 parent 8d05a04 commit 312ee79
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
67 changes: 67 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,73 @@

Python stub file (`*.pyi`) generator for PyO3 based projects.

# Usage

This crate provides a procedural macro `#[gen_stub_pyfunction]` and others to generate a Python stub file.
It is used with PyO3's `#[pyfunction]` macro. Let's consider a simple example PyO3 project:

```rust
use pyo3::prelude::*;

#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
Ok((a + b).to_string())
}

#[pymodule]
fn pyo3_stub_gen_testing(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
Ok(())
}
```

To generate a stub file for this project, please modify it as follows:

```rust
use pyo3::prelude::*;
use pyo3_stub_gen::{derive::gen_stub_pyfunction, StubInfo};
use std::{env, path::*};

#[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 pyo3_stub_gen_testing(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
Ok(())
}

/// Create stub file generator `StubInfo` for this project
pub fn stub_info() -> pyo3_stub_gen::Result<StubInfo> {
let manifest_dir: &Path = env!("CARGO_MANIFEST_DIR").as_ref();
// Get Python project name from pyproject.toml
StubInfo::from_pyproject_toml(manifest_dir.join("pyproject.toml"))
}
```

And then, create an executable target in `src/bin/stub_gen.rs`:

```rust
use pyo3_stub_gen::Result;

fn main() -> Result<()> {
let stub = pyo3_stub_gen_testing::stub_info()?;
stub.generate_single_stub_file(env!("CARGO_MANIFEST_DIR"))?;
Ok(())
}
```

This target generates a stub file `${CARGO_MANIFEST_DIR}/pyo3_stub_gen_testing.pyi` when executed.

```shell
cargo run --bin stub_gen
```

The stub file is automatically found by `maturin`, and it is included in the wheel package. See also the [maturin document](https://www.maturin.rs/project_layout#adding-python-type-information) for more details.

# License

© 2024 Jij Inc.
Expand Down
3 changes: 3 additions & 0 deletions pyo3-stub-gen-testing/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#[doc = include_str!("../../README.md")]
mod readme {}

use pyo3::prelude::*;
use pyo3_stub_gen::{derive::gen_stub_pyfunction, StubInfo};
use std::{env, path::*};
Expand Down

0 comments on commit 312ee79

Please sign in to comment.