Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Syntax Error #293

Open
LazerJesus opened this issue Jun 13, 2023 · 3 comments
Open

Syntax Error #293

LazerJesus opened this issue Jun 13, 2023 · 3 comments

Comments

@LazerJesus
Copy link

I run this little snipped

    let code_input = format!("def sum(a, b):\n  return a + b");
    let code_test = format!("\nresult = sum(1, 2)\nprint(result)",);
    let code = format!(
        r#"{}
{}"#,
        code_input, code_test
    );

    let result: Result<PyObject, PyErr> = py.eval(&code, None, None);

    println!("CODE: \n{}", code);
    println!("OUTPUT: \n{result:#?}\n");

And this is the result:

CODE: 
def sum(a, b):
  return a + b

result = sum(1, 2)
print(result)

OUTPUT: 
Err(
    PyErr {
        ptype: <class 'SyntaxError'>,
        pvalue: Some(
            ('invalid syntax', ('<string>', 1, 1, 'def sum(a, b):\n', 1, 4)),
        ),
        ptraceback: None,
    },
)

Where is the invalid syntax coming from?
if i copy paste the code into a python repl, it executes.

def sum(a, b):
  return a + b

result = sum(1, 2)
print(result)
@ssokolow
Copy link

ssokolow commented Jun 13, 2023

Python has a distinction between eval and exec, with the former only accepting expressions, not statements.

This is the REPL equivalent to what you asked rust-cpython to do:

>>> eval("""def sum(a, b):
...   return a + b
... 
... result = sum(1, 2)
... print(result)""")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    def sum(a, b):
    ^
SyntaxError: invalid syntax

I follow the extend, don't embed philosophy for combining Python with other languages, so, off the top of my head, I don't know how to exec.

EDIT: I believe what you're looking for is Python::run. (Try changing your code from py.eval to py.run and fixing any function signature errors that result.)

@LazerJesus
Copy link
Author

Python::run is indeed executing, thank you.
But another problem pops up. The value is just printed to the console.
The signature is let result: Result<(), PyErr> = py.run(&code, None, None);
No return value. any idea off the top off your head how to capture that?

@ssokolow
Copy link

It depends on what you're trying to do but, typically, I'd go:

  1. Use Python.run for the def and other such "setup" stuff.
  2. Use Python.eval for the sum(1, 2) function call where you want to capture the return value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants