Audrey M. Roy Greenfeld

Quietly building the future.

PyO3, and Bringing Rust HashMap to Python

2024-07-10

PyO3 is awesome: you can use it to bring existing or new Rust code to Python, so you can use it in your Python projects.

As a playful little experiment, I thought I'd try bringing Rust's HashMap to Python using PyO3.

I called the new Python class/package OxiDict.

python3 -m venv .venv
source .venv/bin/activate
pip install -U pip maturin
maturin new -b pyo3 oxidict

The Maturin tutorial says to edit Cargo.toml to add abi3-py38. I thought I'd use min 3.10 since that works for my needs.

...
[dependencies.pyo3]
version = "0.22.0"
# "abi3-py310" tells pyo3 (and maturin) to build using the stable ABI with minimum Python version 3.10
features = ["abi3-py310"]

More info: https://pyo3.rs/main/building-and-distribution#minimum-python-version-for-abi3

(I ended up not doing that in my OxiDict package for now, but I'll likely change it later.)

Edit src/lib.rs to add a hashmap:

use pyo3::prelude::*;
use std::collections::HashMap;

#[pyclass]
struct OxiDict {
    map: HashMap<String, String>,
}

Then add methods and wrap them in a Python module.

Reflection

Again, this was just an experiment to see if I could actually bring a Rust class to Python so I could import and use it.

Python dicts are fast, elegant, and optimized, and there's probably no real need to bring Rust HashMap to Python. But maybe a use case for OxiDict or something inspired by it will come up. You never know.

See https://github.com/feldroy/oxidict for the full code.