Skip to main content

Module ordered_float

Module ordered_float 

Source
Available on crate feature ordered-float only.
Expand description

Conversions to and from ordered-float types. [NotNan]<f32> and [NotNan]<f64>. [OrderedFloat]<f32> and [OrderedFloat]<f64>.

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

Take care when comparing sorted collections of float types between Python and Rust. They will likely differ due to the ambiguous sort order of NaNs in Python.

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

[dependencies]
pyo3 = { version = "0.30.0", features = ["ordered-float"] }
ordered-float = "5.0.0"

Β§Example

Rust code to create functions that add ordered floats:

use ordered_float::{NotNan, OrderedFloat};
use pyo3::prelude::*;

#[pyfunction]
fn add_not_nans(a: NotNan<f64>, b: NotNan<f64>) -> NotNan<f64> {
    a + b
}

#[pyfunction]
fn add_ordered_floats(a: OrderedFloat<f64>, b: OrderedFloat<f64>) -> OrderedFloat<f64> {
    a + b
}

#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(add_not_nans, m)?)?;
    m.add_function(wrap_pyfunction!(add_ordered_floats, m)?)?;
    Ok(())
}

Python code that validates the functionality:

from my_module import add_not_nans, add_ordered_floats

assert add_not_nans(1.0,2.0) == 3.0
assert add_ordered_floats(1.0,2.0) == 3.0

Re-exportsΒ§

use crate::conversion::IntoPyObject; πŸ”’
use crate::exceptions::PyValueError; πŸ”’
use crate::inspect::PyStaticExpr; πŸ”’ experimental-inspect
use crate::types::PyFloat; πŸ”’
use crate::Borrowed; πŸ”’
use crate::Bound; πŸ”’
use crate::FromPyObject; πŸ”’
use crate::FromPyObject; πŸ”’
use crate::PyAny; πŸ”’
use crate::Python; πŸ”’
use core::convert::Infallible; πŸ”’
use ordered_float::NotNan; πŸ”’
use ordered_float::OrderedFloat; πŸ”’
use crate::platform::prelude::*; πŸ”’

MacrosΒ§

float_conversions πŸ”’
⚠️ Internal Docs ⚠️ Not Public API πŸ‘‰ Official Docs Here