Skip to main content

Module uuid

Module uuid 

Source
Available on crate feature uuid only.
Expand description

Conversions to and from uuid’s Uuid and NonNilUuid types.

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

§Setup

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

[dependencies]
pyo3 = { version = "0.28.3", features = ["uuid"] }
uuid = "1.11.0"

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

§Example

Rust code to create a function that parses a UUID string and returns it as a Uuid:

use pyo3::prelude::*;
use pyo3::exceptions::PyValueError;
use uuid::Uuid;

/// Parse a UUID from a string.
#[pyfunction]
fn get_uuid_from_str(s: &str) -> PyResult<Uuid> {
    Uuid::parse_str(s).map_err(|e| PyValueError::new_err(e.to_string()))
}

/// Passing a Python uuid.UUID directly to Rust.
#[pyfunction]
fn get_uuid(u: Uuid) -> Uuid {
    u
}

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

Python code that validates the functionality

from my_module import get_uuid_from_str, get_uuid
import uuid

py_uuid = uuid.uuid4()

# Convert string to Rust Uuid
rust_uuid = get_uuid_from_str(str(py_uuid))
assert py_uuid == rust_uuid

# Pass Python UUID directly to Rust
returned_uuid = get_uuid(py_uuid)
assert py_uuid == returned_uuid

Functions§

get_uuid_cls 🔒
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here