Skip to content

Instantly share code, notes, and snippets.

@internetimagery
Last active June 22, 2019 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save internetimagery/2806274284a80be6ff591ab422a7d695 to your computer and use it in GitHub Desktop.
Save internetimagery/2806274284a80be6ff591ab422a7d695 to your computer and use it in GitHub Desktop.
Some examples of rust to python using cpython (for my own reference)
[package]
name = "my_module"
version = "0.1.0"
authors = ["Jason Dixon <--->"]
edition = "2018"
[lib]
name = "my_module"
crate-type = ["cdylib"]
[dependencies.cpython]
version = "0.2"
features = ["extension-module"]
[dependencies]
#[macro_use] extern crate cpython;
use cpython::{PyResult, Python, PyErr, PyObject};
use cpython::exc::RuntimeError;
use std::thread::sleep;
use std::time::Duration;
py_class!(class MyClass |py| {
data some_data: String;
def __new__(_cls, data: String) -> PyResult<MyClass> {
MyClass::create_instance(py, data)
}
@classmethod def from_int(_cls, data: i32) -> PyResult<MyClass> {
MyClass::create_instance(py, data.to_string())
}
def get_data(&self) -> PyResult<String> {
let data = self.some_data(py).clone();
Ok(data)
}
def __repr__(&self) -> PyResult<String> {
Ok(format!("MyClass <{}>", self.some_data(py)))
}
def sleep(&self) -> PyResult<PyObject> {
// Drop the GIL to do some work.
py.allow_threads(|| {
println!("About to nap...");
sleep(Duration::from_secs(4));
println!("Waking up!");
});
Ok(py.None())
}
def error(&self, doit: bool) -> PyResult<PyObject> {
if doit {
Err(PyErr::new::<RuntimeError, _>(py, "Oops, what an error."))
} else {
Ok(py.None())
}
}
def version(&self) -> PyResult<String> {
let sys = py.import("sys")?;
Ok(sys.get(py, "version")?.extract(py)?)
}
});
fn my_function(_: Python, name: &str) -> PyResult<String> {
Ok(format!("Hello {}", name))
}
// May need "libmy_module"
py_module_initializer!(libmy_module, initlibmy_module, PyInit_my_module, |py, m| {
m.add(py, "__doc__", "This module is implemented in Rust.")?;
m.add(py, "my_function", py_fn!(py, my_function(name: &str)))?;
m.add_class::<MyClass>(py)?;
Ok(())
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment