GithubHelp home page GithubHelp logo

aeshirey / cheeseshop Goto Github PK

View Code? Open in Web Editor NEW
1.0 2.0 0.0 35 KB

Examples of using PyO3 Rust bindings for Python with little to no silliness.

License: MIT License

Rust 75.83% Python 24.17%
pyo3-rust-bindings python rust-library rust rust-bindings

cheeseshop's Introduction

CheeseShop

Examples of using PyO3 Rust bindings for Python with little to no silliness. For detailed documentation, see the PyO3 user guide. This project uses the current version (0.19.2) as of 2023-09-11.

Getting Started

  • Create your library project: $ cargo new --lib CheeseShop

Update your Cargo.toml:

[lib]
name = "CheeseShop"
crate-type = ["cdylib"]

[dependencies]
pyo3 = { version = "0.19.2", features = ["extension-module"] }

Here, name sets the name of the output library. In Linux, this compiles to libCheeseShop.so. This must be renamed to CheeseShop.so, which lets you import CheeseShop in Python.

Running Code in This Project

There's an example_usage.py file that invokes the Rust methods. For example:

from CheeseShop import *
>>> do_something()
['And', 'now', 'for', 'something', 'completely', 'different']
>>> movies()
[('Monty Python and the Holy Grail', 1975), ('Life of Brian', 1979), ('The Meaning of Life', 1983)]

Writing Rust functions

Some simple examples of Rust functions that become available in Python:

use pyo3::prelude::*;

#[pyfunction]
/// Does something completely different by returning a Python `List[str]`.
fn do_something() -> Vec<&'static str> {
    "And now for something completely different"
        .split(" ")
        .collect()
}

#[pyfunction]
/// A module-level function that simply returns tuples of movies and their release year.
fn movies() -> Vec<(String, u16)> {
    vec![
        ("Monty Python and the Holy Grail".to_string(), 1975),
        ("Life of Brian".to_string(), 1979),
        ("The Meaning of Life".to_string(), 1983),
    ]
}

#[pymodule]
fn CheeseShop(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_wrapped(wrap_pyfunction!(do_something))?;
    m.add_wrapped(wrap_pyfunction!(movies))?;
}

The /// Rust doc comments turn into Python docstrings, so calling help(movies) for the above function will show you this in the Python REPL:

Help on built-in function movies:

movies()
    A module-level function that simply returns tuples of movies and their release year.

Attributes

PyO3 provides numerous attributes for conveniently mapping your Rust code to comparable Python functionality:

Python Classes

  • #[pyclass] marks a struct (or fieldless enum) as a Python class
  • #[pymethods] marks one impl block for that struct (or enum). Functions/methods are generally accessible in Python, and they don't need pub modifiers on them.
  • #[new] makes a Rust function (within the pymethods block) into the __init__ constructor for a class
  • Magic (or sometimes called 'dunder') methods are declared like other methods. Your implementation will need the approprate number and type of arguments and return values; for example:
    • fn __setattr__(&self) {} will fail to compile with the error, Expected 2 arguments, got 0 because setattr requires two inputs.
    • fn __setattr__(&self, name: i32, value: i32) {} will fail at runtime with the error, argument 'name': 'str' object cannot be interpreted as an integer because the name argument is of an incorrect type
    • fn __setattr__(&self, name: i32, value: i32) -> bool {} will fail to compile because this magic method is expected to have no return value (or, technically, unit).
  • #[staticmethod] marks an associated Rust function as being a Python static method

Signatures

By default, methods and functions have basic help documentation that includes argument names. You can use #[pyo3(text_signature = "...")] to override this auto-generated text; the provided string is arbitrary and is simply appended to the end of the function name; it is expected that your text_signature encloses argumens in parentheses; eg, (name: str, age: int = None).

To supply your own default values, to handle *args and **kwargs, and more, use #[pyo3(signature = (...))]. The argument names in this attribute must match the names used in the Rust function it annotates, and the default values (if provided) must be valid Rust code that corresponds to theinput type.

cheeseshop's People

Contributors

aeshirey avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.