Module pyo3::rust_decimal

source ·
Expand description

Conversions to and from rust_decimal’s [Decimal] type.

This is useful for converting Python’s decimal.Decimal into and from a native Rust type.


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

pyo3 = { version = "0.21.2", features = ["rust_decimal"] }
rust_decimal = "1.0"

Note that you must use a compatible version of rust_decimal and PyO3. The required rust_decimal version may vary based on the version of PyO3.


Rust code to create a function that adds one to a Decimal

use rust_decimal::Decimal;
use pyo3::prelude::*;

fn add_one(d: Decimal) -> Decimal {
    d + Decimal::ONE

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

Python code that validates the functionality

from my_module import add_one
from decimal import Decimal

d = Decimal("2")
value = add_one(d)

assert d + 1 == value