Home

Awesome

inline-python

Inline Python code directly in your Rust code.

Example

use inline_python::python;

fn main() {
    let who = "world";
    let n = 5;
    python! {
        for i in range('n):
            print(i, "Hello", 'who)
        print("Goodbye")
    }
}

How to use

Use the python!{..} macro to write Python code directly in your Rust code.

NOTE: Rust nightly toolchain is required. Feature proc_macro_span is still unstable, for more details check out issue #54725 - Tracking issue for proc_macro::Span inspection APIs

Using Rust variables

To reference Rust variables, use 'var, as shown in the example above. var needs to implement pyo3::ToPyObject.

Re-using a Python context

It is possible to create a Context object ahead of time and use it for running the Python code. The context can be re-used for multiple invocations to share global variables across macro calls.

let c = Context::new();

c.run(python! {
  foo = 5
});

c.run(python! {
  assert foo == 5
});

As a shortcut, you can assign a python!{} invocation directly to a variable of type Context to create a new context and run the Python code in it.

let c: Context = python! {
  foo = 5
};

c.run(python! {
  assert foo == 5
});

Getting information back

A Context object could also be used to pass information back to Rust, as you can retrieve the global Python variables from the context through Context::get.

let c: Context = python! {
  foo = 5
};

assert_eq!(c.get::<i32>("foo"), 5);

Syntax issues

Since the Rust tokenizer will tokenize the Python code, some valid Python code is rejected. The two main things to remember are:

Other minor things that don't work are:

Everything else should work fine.