setuptools-rust

1.12.1 · active · verified Thu Apr 09

setuptools-rust is a setuptools extension plugin that simplifies the integration of Rust code compilation and packaging into Python projects, especially those leveraging PyO3. It handles the build process for Rust extensions, making it easier to distribute Python packages with native Rust components. The library is actively maintained, currently at version 1.12.1, with a regular release cadence to support new Python and Rust features.

Warnings

Install

Imports

Quickstart

This quickstart provides a `setup.py` example for building a Rust extension using `setuptools-rust`. It defines a `RustExtension` for `my_rust_package.my_module`, pointing to a `Cargo.toml`. Accompanying `pyproject.toml`, `Cargo.toml`, `my_rust_package/__init__.py`, and `src/lib.rs` file structures are commented within the code, demonstrating how to integrate a simple PyO3 Rust function into a Python package. After setting up these files, the project can be built and installed using `pip install .`.

from setuptools import setup
from setuptools_rust import RustExtension

setup(
    name='my_rust_package',
    version='0.1.0',
    rust_extensions=[
        RustExtension(
            'my_rust_package.my_module',
            './Cargo.toml',
            # debug=True, # Uncomment for debug builds
            # features=['some_feature'], # Optional Cargo features
        )
    ],
    packages=['my_rust_package'],
)

# To make this example runnable, ensure the following files exist:
#
# pyproject.toml:
# [build-system]
# requires = ["setuptools>=61.0.0", "setuptools-rust>=1.0.0", "wheel"]
# build-backend = "setuptools.build_meta"
#
# Cargo.toml (at the project root, or specified path './Cargo.toml'):
# [package]
# name = "my_module"
# version = "0.1.0"
# edition = "2021"
#
# [lib]
# name = "my_module"
# crate-type = ["cdylib"]
#
# [dependencies]
# pyo3 = { version = "0.21.2", features = ["extension-module"] }
#
# my_rust_package/__init__.py (empty or `from .my_module import *`):
#
# src/lib.rs (for the Rust extension):
# use pyo3::prelude::*;
#
# #[pyfunction]
# fn greet(name: &str) -> PyResult<String> {
#     Ok(format!("Hello, {} from Rust!", name))
# }
#
# #[pymodule]
# fn my_module(_py: Python, m: &PyModule) -> PyResult<()> {
#     m.add_function(wrap_pyfunction!(greet, m)?)?;
#     Ok(())
# }

view raw JSON →