m-ou-se / inline-python

Inline Python code directly in your Rust code
https://docs.rs/inline-python
BSD 2-Clause "Simplified" License
1.16k stars 40 forks source link

Put Rust variables in a global RUST variable for python. #6

Closed de-vri-es closed 5 years ago

de-vri-es commented 5 years ago

This allows the variables to be accessed from inside local function definitions. It also reduces the potential conflict with the python script to a single global variable.

For example:

fn main() {
  let data = vec![(4, 3), (2, 8), (3, 1), (4, 0)];
  python! {
    import matplotlib.pyplot as plt
    def foo():
      plt.plot('data)
      plt.show()
    foo()
  }
}

Without this PR, that results in:

Traceback (most recent call last):
  File "inline-python-example/src/main.rs", line 12, in <module>
    foo()
  File "inline-python-example/src/main.rs", line 10, in foo
    plt.plot('data)
NameError: name 'plt' is not defined
thread 'main' panicked at 'python!{...} failed to execute', inline-python-example/src/main.rs:7:2

With the PR, it works as expected. Weirdly, it's not complaining about _rust_data but about plt. Not sure why that happens to be honest. It seems to be "fixed" by passing null as locals to PyEval_EvalCode.