|
| 1 | +# Calling Rust from Python |
| 2 | +## Structure |
| 3 | +```rust, ignore |
| 4 | +use rustpython::vm::pymodule; |
| 5 | +#[pymodule] |
| 6 | +mod test_module { |
| 7 | + #[pyattr] |
| 8 | + pub const THE_ANSWER: i32 = 42; |
| 9 | +
|
| 10 | + #[pyfunction] |
| 11 | + pub fn add(a: i32, b: i32) -> i32 { |
| 12 | + a + b |
| 13 | + } |
| 14 | +
|
| 15 | + #[pyattr] |
| 16 | + #[pyclass] |
| 17 | + pub struct TestClass { |
| 18 | + pub value: i32, |
| 19 | + } |
| 20 | +
|
| 21 | + #[pyclass] |
| 22 | + impl TestClass { |
| 23 | + #[pygetset] |
| 24 | + pub fn value(&self) -> i32 { |
| 25 | + self.value |
| 26 | + } |
| 27 | +
|
| 28 | + #[pymethod] |
| 29 | + pub fn get_info(&self) -> i32 { |
| 30 | + self.value * 2 |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | +``` |
| 35 | +This code defines a Python module named `test_module` with two items: |
| 36 | +a constant named `THE_ANSWER` and a function named `add`. |
| 37 | +The `#[pymodule]` attribute is used to mark the module, |
| 38 | +and the `#[pyattr]` and `#[pyfunction]` attributes are used to mark the constant and function, respectively. |
| 39 | + |
| 40 | +RustPython allows for 3 types of items in a module: |
| 41 | +- Variables: Defined using the `#[pyattr]` attribute. |
| 42 | +- Functions: Defined using the `#[pyfunction]` attribute. |
| 43 | +- Classes: Defined using the `#[pyclass]` attribute. |
| 44 | + |
| 45 | +## General Configuration |
| 46 | +Most attributes have a `name` parameter that can be used to specify the name of the item in Python. |
| 47 | +If the `name` parameter is not provided, the Rust identifier is used as the name in Python. |
| 48 | + |
| 49 | +## Variables |
| 50 | +Variables are defined using the `#[pyattr]` attribute. |
| 51 | +A variable can either be a constant or a function. |
| 52 | +Note that classes are treated as attributes in RustPython |
| 53 | +and are annotated with `#[pyattr]` as well, but that can be done away with if needed. |
| 54 | +```rust, no_run |
| 55 | +#[pyattr] |
| 56 | +const THE_ANSWER: i32 = 42; |
| 57 | +// ... or |
| 58 | +#[pyattr] |
| 59 | +fn the_answer() -> i32 { |
| 60 | + 42 |
| 61 | +} |
| 62 | +// ... or |
| 63 | +// this will cache the result of the function |
| 64 | +// and return the same value every time it is called |
| 65 | +#[pyattr(once)] |
| 66 | +fn cached_answer() -> i32 { |
| 67 | + 42 |
| 68 | +} |
| 69 | +``` |
| 70 | + |
| 71 | +## Valid Arguments/Return Types |
| 72 | +Every input and return value must be convertible to `PyResult`. This is defined as `IntoPyResult` trait. So any return value of them must implement `IntoPyResult`. It will be `PyResult<PyObjectRef>`, `PyObjectRef` and any `PyResult<T>` when T implements `IntoPyObject`. Practically we can list them like: |
| 73 | +- Any `T` when `PyResult<T>` is possible |
| 74 | +- `PyObjectRef` |
| 75 | +- `PyResult<()>` and `()` as `None` |
| 76 | +- `PyRef<T: PyValue>` like `PyIntRef`, `PyStrRef` |
| 77 | +- `T: PyValue` like `PyInt`, `PyStr` |
| 78 | +- Numbers like `usize` or `f64` for `PyInt` and `PyFloat` |
| 79 | +- `String` for `PyStr` |
| 80 | +- And more types implementing `IntoPyObject`. |
| 81 | + |
| 82 | +The `vm` paramter is optional. We add it as the last parameter unless we don't use `vm` at all - very rare case. It takes an object `obj` as `PyObjectRef`, which is a general python object. It returns `PyResult<String>`, which will turn into `PyResult<PyObjectRef>` the same representation of `PyResult`. The `vm` parameter does not need to be passed in by the python code. |
| 83 | + |
| 84 | +If needed a seperate struct can be used for arguments using the `FromArgs` trait like so: |
| 85 | + |
| 86 | +```rust |
| 87 | +#[derive(FromArgs)] |
| 88 | +struct BisectArgs { |
| 89 | + a: PyObjectRef, |
| 90 | + x: PyObjectRef |
| 91 | + #[pyarg(any, optional)] |
| 92 | + lo: OptionalArg<ArgIndex>, |
| 93 | + #[pyarg(any, optional)] |
| 94 | + hi: OptionalArg<ArgIndex>, |
| 95 | + #[pyarg(named, default)] |
| 96 | + key: Option<PyObjectRef>, |
| 97 | +} |
| 98 | + |
| 99 | +#[pyfunction] |
| 100 | +fn bisect_left( |
| 101 | + BisectArgs { a, x, lo, hi, key }: BisectArgs, |
| 102 | + vm: &VirtualMachine, |
| 103 | +) -> PyResult<usize> { |
| 104 | + // ... |
| 105 | +} |
| 106 | + |
| 107 | +// or ... |
| 108 | + |
| 109 | +#[pyfunction] |
| 110 | +fn bisect_left( |
| 111 | + args: BisectArgs, |
| 112 | + vm: &VirtualMachine, |
| 113 | +) -> PyResult<usize> { |
| 114 | + // ... |
| 115 | +} |
| 116 | +``` |
| 117 | + |
| 118 | +## Errors |
| 119 | + |
| 120 | +Returning a PyResult is the supported error handling strategy. Builtin python errors are created with `vm.new_xxx_error` methods. |
| 121 | + |
| 122 | +### Custom Errors |
| 123 | + |
| 124 | +``` |
| 125 | +#[pyattr(once)] |
| 126 | +fn error(vm: &VirtualMachine) -> PyTypeRef { |
| 127 | + vm.ctx.new_exception_type( |
| 128 | + "<module_name>", |
| 129 | + "<error_name>", |
| 130 | + Some(vec![vm.ctx.exceptions.exception_type.to_owned()]), |
| 131 | + ) |
| 132 | +} |
| 133 | +
|
| 134 | +// convenience function |
| 135 | +fn new_error(message: &str, vm: &VirtualMachine) -> PyBaseExceptionRef { |
| 136 | + vm.new_exception_msg(vm.class("<module_name>", "<error_name>"), message.to_owned()) |
| 137 | +} |
| 138 | +``` |
| 139 | + |
| 140 | +## Functions |
| 141 | +Functions are defined using the `#[pyfunction]` attribute. |
| 142 | +```rust, no_run |
| 143 | +#[pyfunction] |
| 144 | +fn add(a: i32, b: i32) -> i32 { |
| 145 | + a + b |
| 146 | +} |
| 147 | +``` |
| 148 | + |
| 149 | +## Classes |
| 150 | +Classes are defined using the `#[pyclass]` attribute. |
| 151 | +```rust, no_run |
| 152 | +#[pyclass] |
| 153 | +pub struct TestClass { |
| 154 | + pub value: i32, |
| 155 | +} |
| 156 | +#[pyclass] |
| 157 | +impl TestClass { |
| 158 | +} |
| 159 | +``` |
| 160 | +### Associated Data |
| 161 | +TODO. |
| 162 | +### Methods |
| 163 | +TODO. |
| 164 | +### Getters and Setters |
| 165 | +TODO. |
| 166 | +### Class Methods |
| 167 | +TODO. |
| 168 | +### Static Methods |
| 169 | +TODO. |
| 170 | +### Inheritance |
| 171 | +TODO. |
0 commit comments