{"name":"PyO3: Seamless Rust Bindings for the Python Interpreter","description":"PyO3 provides comprehensive Rust bindings for the Python interpreter, enabling developers to create native Python extension modules with Rust. It also supports running and interacting with Python code directly from Rust binaries. This powerful library allows for leveraging Rust's performance and safety within Python applications, bridging the gap between two robust ecosystems.","github":"https://github.com/PyO3/pyo3","url":"https://osrepos.com/repo/pyo3-pyo3","source":"osrepos.com","sourceDescription":"This repository profile is provided by osrepos.com, an open source repository discovery platform.","repositoryProfile":"https://osrepos.com/repo/pyo3-pyo3","generatedFor":"open source discovery and AI-assisted research","markdown":"https://osrepos.com/repo/pyo3-pyo3.md","json":"https://osrepos.com/repo/pyo3-pyo3.json","topics":["binding","ffi","python","python-c-api","rust","interoperability","performance","development"],"keywords":["binding","ffi","python","python-c-api","rust","interoperability","performance","development"],"stars":null,"summary":"PyO3 provides comprehensive Rust bindings for the Python interpreter, enabling developers to create native Python extension modules with Rust. It also supports running and interacting with Python code directly from Rust binaries. This powerful library allows for leveraging Rust's performance and safety within Python applications, bridging the gap between two robust ecosystems.","content":"## Introduction\n\nPyO3 is a robust and widely-used library that provides Rust bindings for the Python interpreter. It empowers developers to write high-performance native Python extension modules entirely in Rust, taking advantage of Rust's speed, memory safety, and concurrency features. Beyond creating Python modules, PyO3 also facilitates embedding and interacting with Python code directly from Rust applications, offering a versatile solution for interoperability between these two powerful languages.\n\n## Installation\n\nPyO3 supports various Python distributions, including CPython 3.7+, PyPy 7.3 (Python 3.11+), and GraalPy 25.0+ (Python 3.12+). The installation process varies slightly depending on whether you're using Rust from Python or Python from Rust.\n\n### Using Rust from Python\n\nThe easiest way to get started with PyO3 for creating native Python modules is by using [`maturin`](https://github.com/PyO3/maturin?target=_blank), a tool designed for building and publishing Rust-based Python packages. Here's a quick setup:\n\n1.  **Create a project and virtual environment:**\n\n    bash\n    mkdir my_rust_module\n    cd my_rust_module\n    python -m venv .env\n    source .env/bin/activate\n    pip install maturin\n    \n\n2.  **Initialize your project with `maturin`:**\n\n    bash\n    maturin init\n    # Select 'pyo3' when prompted for bindings.\n    \n\n    This generates `Cargo.toml` and `src/lib.rs`. A minimal `src/lib.rs` might look like this:\n\n    rust\n    use pyo3::prelude::*;\n\n    #[pyo3::pymodule]\n    fn my_rust_module(_py: Python<'_>, m: &PyModule) -> PyResult<()> {\n        m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;\n        Ok(())\n    }\n\n    #[pyfunction]\n    fn sum_as_string(a: usize, b: usize) -> PyResult<String> {\n        Ok((a + b).to_string())\n    }\n    \n\n3.  **Build and install:**\n\n    bash\n    maturin develop\n    \n\n    Now you can import and use your Rust-powered module in Python:\n\n    python\n    >>> import my_rust_module\n    >>> my_rust_module.sum_as_string(5, 20)\n    '25'\n    \n\n### Using Python from Rust\n\nTo embed a Python interpreter within a Rust binary, you'll need the Python shared library installed on your system. For Ubuntu, use `sudo apt install python3-dev`, and for RPM-based distributions, install `python3-devel`.\n\nThen, add `pyo3` to your `Cargo.toml` with the `auto-initialize` feature:\n\ntoml\n[dependencies.pyo3]\nversion = \"0.27.2\"\nfeatures = [\"auto-initialize\"]\n\n\nHere's an example of running Python code from Rust:\n\nrust\nuse pyo3::prelude::*;\nuse pyo3::types::IntoPyDict;\n\nfn main() -> PyResult<()> {\n    Python::attach(|py| {\n        let sys = py.import(\"sys\")?;\n        let version: String = sys.getattr(\"version\")?.extract()?;\n\n        let locals = [(\"os\", py.import(\"os\")?)].into_py_dict(py)?;\n        let code = \"os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'\";\n        let user: String = py.eval(code, None, Some(&locals))?.extract()?;\n\n        println!(\"Hello {}, I'm Python {}\", user, version);\n        Ok(())\n    })\n}\n\n\n## Examples\n\nPyO3 is utilized in a wide array of projects, demonstrating its versatility and impact. Some notable examples include:\n\n*   **[Polars](https://github.com/pola-rs/polars?target=_blank)**: A fast multi-threaded DataFrame library available in Rust, Python, and Node.js.\n*   **[Pydantic-core](https://github.com/pydantic/pydantic-core?target=_blank)**: The core validation logic for the popular Pydantic library, rewritten in Rust for performance.\n*   **[Tiktoken](https://github.com/openai/tiktoken?target=_blank)**: OpenAI's fast BPE tokeniser, used with their models.\n*   **[Tokenizers](https://github.com/huggingface/tokenizers?target=_blank)**: Python bindings for Hugging Face's NLP tokenizers, implemented in Rust.\n*   **[Orjson](https://github.com/ijl/orjson?target=_blank)**: A high-performance Python JSON library.\n\n## Why Use PyO3?\n\nChoosing PyO3 for Python-Rust interoperability offers several compelling advantages:\n\n*   **Performance Boost**: Leverage Rust's unparalleled speed for computationally intensive tasks, offloading critical sections of your Python application to native code.\n*   **Memory Safety**: Benefit from Rust's strong type system and ownership model, eliminating common memory-related bugs and enhancing application stability.\n*   **Seamless Interoperability**: PyO3 provides a natural and idiomatic way to call Rust functions from Python and vice-versa, making the integration feel native to both languages.\n*   **Access to Rust Ecosystem**: Utilize Rust's rich ecosystem of crates, bringing advanced functionalities like efficient data processing, cryptography, and more to your Python projects.\n*   **Robust Tooling**: Supported by tools like `maturin` and `setuptools-rust`, simplifying the build, packaging, and distribution of Rust-powered Python extensions.\n\n## Links\n\n*   **GitHub Repository**: [https://github.com/PyO3/pyo3](https://github.com/PyO3/pyo3?target=_blank)\n*   **User Guide**: [https://pyo3.rs](https://pyo3.rs?target=_blank)\n*   **API Documentation**: [https://docs.rs/pyo3/](https://docs.rs/pyo3/?target=_blank)","metrics":{"detailViews":5,"githubClicks":2},"dates":{"published":null,"modified":"2026-01-04T20:01:01.000Z"}}