1

I'm a Rust newbie exploring language features with the possible result of recommending Rust as a replacement for C/C++ for our next FW iteration. One important topic is Python interop for unit testing and modeling. I've got this far exposing a Rust struct:

#[pyclass]
pub struct RustStruct {
    #[pyo3(get, set)] integer: i32,
    #[pyo3(get, set)] float: f32
}

There are a few things that bother me about this:

  • I have to set the accessibility for every member separately.
  • I have to modify the original struct code to expose it to Python. Unlike pybind11 for instance, where the original struct definition is untouched, and the pybind code exposes it to Python.
  • The code won't compile in a setting where pyo3 is not present.

Ideally, I'd like to be able take existing Rust structures in an application, and say "please expose this to Python for me, in such a way that I can instantiate and modify the Rust structure in Python, and without having to modify the source code for the existing structure".

I hope this all makes sense. Are there ways to get closer to this goal?

Andrew Voelkel
  • 513
  • 4
  • 10
  • 1
    You can probably create an attribute proc macro that expands to `#[cfg(feature = "python-testing")]`-gated `#[pyclasss]` and `#[pyo3(get, set)]`. You still have to change the struct declaration, but only add one line. – Chayim Friedman Nov 07 '22 at 02:19
  • I thought of the idea of gating the py03 attributes, but are you also suggesting that I could create a macro that would automatically add the ```#[pyo3(get, set)]``` to each member declaration? If so, that's an interesting idea, and I'll have to get cracking on my Rust macro skills. – Andrew Voelkel Nov 07 '22 at 16:55
  • Yes. An attribute proc macro can change the item declaration. – Chayim Friedman Nov 07 '22 at 18:26

0 Answers0