Expand description
Conversions to and from num-rational types.
This is useful for converting between Python’s fractions.Fraction into and from a native Rust type.
To use this feature, add to your Cargo.toml
:
[dependencies]
pyo3 = { version = "0.23.0-dev", features = ["num-rational"] }
num-rational = "0.4.1"
§Example
Rust code to create a function that adds five to a fraction:
use num_rational::Ratio;
use pyo3::prelude::*;
#[pyfunction]
fn add_five_to_fraction(fraction: Ratio<i32>) -> Ratio<i32> {
fraction + Ratio::new(5, 1)
}
#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(add_five_to_fraction, m)?)?;
Ok(())
}
Python code that validates the functionality:
from my_module import add_five_to_fraction
from fractions import Fraction
fraction = Fraction(2,1)
fraction_plus_five = add_five_to_fraction(f)
assert fraction + 5 == fraction_plus_five