PythonのdecimalモジュールのDecimal型は、PyO3 0.27ではrust_decimalクレートやbigdecimalクレートで扱う。
まず、rust_decimalクレートを依存ライブラリーに追加する。
cd example-pyo3 cargo add rust_decimal
次に、pyo3にrust_decimalフィーチャーを追加する。
〜
[dependencies]
pyo3 = { version = "0.27.2", features = ["rust_decimal"] }
rust_decimal = "1.39.0"
use pyo3::prelude::*;
#[pymodule]
mod example_pyo3 {
use pyo3::{prelude::*};
〜
#[pyfunction]
fn inc_decimal(value: rust_decimal::Decimal) -> PyResult<rust_decimal::Decimal> {
let value = value + rust_decimal::Decimal::ONE;
Ok(value)
}
}
import example_pyo3
def main():
print("Hello from call-pyo3!")
print(example_pyo3.inc_decimal(123.4))
if __name__ == "__main__":
main()
> cd call-pyo3 > uv run main.py Hello from call-pyo3! 124.4
まず、bigdecimalクレートを依存ライブラリーに追加する。
cd example-pyo3 cargo add bigdecimal
次に、pyo3にbigdecimalフィーチャーを追加する。
〜
[dependencies]
bigdecimal = "0.4.9"
pyo3 = { version = "0.27.2", features = ["bigdecimal"] }
use pyo3::prelude::*;
#[pymodule]
mod example_pyo3 {
use pyo3::{prelude::*};
〜
#[pyfunction]
fn inc_decimal(value: bigdecimal::BigDecimal) -> PyResult<bigdecimal::BigDecimal> {
let value = value + 1;
Ok(value)
}
}