-
Notifications
You must be signed in to change notification settings - Fork 4
Python in Rust
RustyPy requires Python 3.5 at least, and the functions that will be binded need to be type annotated. You can check the type conversions between Python and Rust at the type conversions page. RustyPy back-end in Rust the Rust-CPython library.
Assume the following package structure:
/example_package/
|
|__/test/
| |...
|__/src/
/subdir/
||__ sub.py
|__ __init__.py
|__ funcs.py
|__ lib.rs
The content of funcs.py is:
from rustypy include rust_bind
@rust_bind
def add_one(arg: int) -> int:
result = arg + 1
return result
def rust_bind_hello() -> None:
print('Hello from Rust!')
The content of sub.py is:
from rustypy include rust_bind
@rust_bind
def print_something(arg: str) -> None:
print(str)
Any function which has one of the specified prefixes (default is rust_bind_) prefix or decorated by the rust_bind decorator will be parsed and a new file (rustypy_pybind.rs) containing the bindings will be generated at the package root (in this case in /example_package/src/rustypy_pybind.rs).
Then we call rustypy:
$ rustypy --prefixes my_func_prefix_ an_other_prefix -p python /example_package/src
or
$ cd example_package
example_package$ pip install -e .
example_package$ rustypy --prefixes my_func_prefix_ an_other_prefix -p python example_package
The second form installs our package in development mode, in this case we can just provide the name of the package instead of the absolute path to it.
To use our package from Rust we just have to import the package manager in the wanted module (lib.rs for example):
extern crate cpython;
mod rustypy_pybind;
use rustypy_pybind::PyModules;
use cpython::Python;
// setup Python interpreter
let gil = Python::acquire_gil();
let py = gil.python();
// setup the module manager
let example_package = PyModules::new(&py);
// call functions
example_package.funcs.rust_bind_hello();
let num = 10;
let result = example_package.funcs.add_one(num);
assert_eq!(11, result);
let arg = String::from("Hello from Rust!");
example_package.subdir.sub.print_something(arg);
The module manager uses object notation to structure the subpackages and functions. For more examples you can check the tests directory.