Available on crate feature
num-bigint
only.Expand description
Conversions to and from num-bigint’s BigInt
and BigUint
types.
This is useful for converting Python integers when they may not fit in Rust’s built-in integer types.
§Setup
To use this feature, add this to your Cargo.toml
:
[dependencies]
num-bigint = "*"
pyo3 = { version = "0.23.3", features = ["num-bigint"] }
Note that you must use compatible versions of num-bigint and PyO3. The required num-bigint version may vary based on the version of PyO3.
§Examples
Using BigInt
to correctly increment an arbitrary precision integer.
This is not possible with Rust’s native integers if the Python integer is too large,
in which case it will fail its conversion and raise OverflowError
.
use num_bigint::BigInt;
use pyo3::prelude::*;
#[pyfunction]
fn add_one(n: BigInt) -> BigInt {
n + 1
}
#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(add_one, m)?)?;
Ok(())
}
Python code:
from my_module import add_one
n = 1 << 1337
value = add_one(n)
assert n + 1 == value