Module pyo3::num_bigint

source ·
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.


To use this feature, add this to your Cargo.toml:

num-bigint = "*"
pyo3 = { version = "0.21.2", 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.


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::*;

fn add_one(n: BigInt) -> BigInt {
    n + 1

fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(add_one, m)?)?;

Python code:

from my_module import add_one

n = 1 << 1337
value = add_one(n)

assert n + 1 == value