inline_python/
lib.rs

1//! Inline Python code directly in your Rust code.
2//!
3//! # Example
4//!
5//! ```
6//! use inline_python::python;
7//!
8//! let who = "world";
9//! let n = 5;
10//! python! {
11//!     for i in range('n):
12//!         print(i, "Hello", 'who)
13//!     print("Goodbye")
14//! }
15//! ```
16//!
17//! # How to use
18//!
19//! Use the `python!{..}` macro to write Python code directly in your Rust code.
20//!
21//! _NOTE:_ This crate uses the **unstable** [`proc_macro_span` feature](https://github.com/rust-lang/rust/issues/54725),
22//! so it will only compile on Rust **nightly**.
23//!
24//! ## Using Rust variables
25//!
26//! To reference Rust variables, use `'var`, as shown in the example above.
27//! `var` needs to implement [`pyo3::IntoPyObject`].
28//!
29//! ## Re-using a Python context
30//!
31//! It is possible to create a [`Context`] object ahead of time and use it for running the Python code.
32//! The context can be re-used for multiple invocations to share global variables across macro calls.
33//!
34//! ```
35//! # use inline_python::{Context, python};
36//! let c = Context::new();
37//!
38//! c.run(python! {
39//!   foo = 5
40//! });
41//!
42//! c.run(python! {
43//!   assert foo == 5
44//! });
45//! ```
46//!
47//! As a shortcut, you can assign a `python!{}` invocation directly to a
48//! variable of type `Context` to create a new context and run the Python code
49//! in it.
50//!
51//! ```
52//! # use inline_python::{Context, python};
53//! let c: Context = python! {
54//!   foo = 5
55//! };
56//!
57//! c.run(python! {
58//!   assert foo == 5
59//! });
60//! ```
61//!
62//! ## Getting information back
63//!
64//! A [`Context`] object could also be used to pass information back to Rust,
65//! as you can retrieve the global Python variables from the context through
66//! [`Context::get`].
67//!
68//! ```
69//! # use inline_python::{Context, python};
70//! let c: Context = python! {
71//!   foo = 5
72//! };
73//!
74//! assert_eq!(c.get::<i32>("foo"), 5);
75//! ```
76//!
77//! ## Syntax issues
78//!
79//! Since the Rust tokenizer will tokenize the Python code, some valid Python
80//! code is rejected. The two main things to remember are:
81//!
82//! - Use double quoted strings (`""`) instead of single quoted strings (`''`).
83//!
84//!   (Single quoted strings only work if they contain a single character, since
85//!   in Rust, `'a'` is a character literal.)
86//!
87//! - Use `//`-comments instead of `#`-comments.
88//!
89//!   (If you use `#` comments, the Rust tokenizer will try to tokenize your
90//!   comment, and complain if your comment doesn't tokenize properly.)
91//!
92//! Other minor things that don't work are:
93//!
94//! - Certain escape codes in string literals.
95//!   (Specifically: `\a`, `\b`, `\f`, `\v`, `\N{..}`, `\123` (octal escape
96//!   codes), `\u`, and `\U`.)
97//!
98//!   These, however, are accepted just fine: `\\`, `\n`, `\t`, `\r`, `\xAB`
99//!   (hex escape codes), and `\0`
100//!
101//! - Raw string literals with escaped double quotes. (E.g. `r"...\"..."`.)
102//!
103//! - Triple-quoted byte- and raw-strings with content that would not be valid
104//!   as a regular string. And the same for raw-byte and raw-format strings.
105//!   (E.g. `b"""\xFF"""`, `r"""\z"""`, `fr"\z"`, `br"\xFF"`.)
106//!
107//! - The `//` and `//=` operators are unusable, as they start a comment.
108//!
109//!   Workaround: you can write `##` instead, which is automatically converted
110//!   to `//`.
111//!
112//! Everything else should work fine.
113
114use pyo3::{types::PyDict, Bound, Python};
115
116mod context;
117mod run;
118
119pub use self::context::Context;
120pub use pyo3;
121
122/// A block of Python code within your Rust code.
123///
124/// This macro can be used in three different ways:
125///
126///  1. By itself as a statement.
127///     In this case, the Python code is executed directly.
128///
129///  2. By assigning it to a [`Context`].
130///     In this case, the Python code is executed directly, and the context
131///     (the global variables) are available for re-use by other Python code
132///     or inspection by Rust code.
133///
134///  3. By passing it as an argument to a function taking a `PythonBlock`, such
135///     as [`Context::run`].
136///
137/// See [the crate's module level documentation](index.html) for examples.
138pub use inline_python_macros::python;
139
140#[doc(hidden)]
141pub trait FromInlinePython<F: FnOnce(&Bound<PyDict>)> {
142	fn from_python_macro(bytecode: &'static [u8], set_variables: F) -> Self;
143}
144
145/// Converting a `python!{}` block to `()` will run the Python code.
146///
147/// This happens when `python!{}` is used as a statement by itself.
148impl<F: FnOnce(&Bound<PyDict>)> FromInlinePython<F> for () {
149	fn from_python_macro(bytecode: &'static [u8], set_variables: F) {
150		let _: Context = FromInlinePython::from_python_macro(bytecode, set_variables);
151	}
152}
153
154/// Assigning a `python!{}` block to a `Context` will run the Python code and capture the resulting context.
155impl<F: FnOnce(&Bound<PyDict>)> FromInlinePython<F> for Context {
156	fn from_python_macro(bytecode: &'static [u8], set_variables: F) -> Self {
157		Python::with_gil(|py| {
158			let context = Context::new_with_gil(py);
159			context.run_with_gil(py, PythonBlock { bytecode, set_variables });
160			context
161		})
162	}
163}
164
165/// Using a `python!{}` block as a `PythonBlock` object will not do anything yet.
166impl<F: FnOnce(&Bound<PyDict>)> FromInlinePython<F> for PythonBlock<F> {
167	fn from_python_macro(bytecode: &'static [u8], set_variables: F) -> Self {
168		Self { bytecode, set_variables }
169	}
170}
171
172/// Represents a `python!{}` block.
173#[doc(hidden)]
174pub struct PythonBlock<F> {
175	bytecode: &'static [u8],
176	set_variables: F,
177}