How to use PythonCall with string literal?

I’m upgrading from older PyCall to PythonCall, but can’t figure out how make it work.

I prefer to use python code as a sting to evaluate, it has nice syntax highlight, looks like normal python code and easy to copy/paste. Like PyCall does. I don’t want to wrap it into julia proxies. Is it possible?

using PythonCall

py"""
def add(a, b):
  return a + b
"""

py"add".(2, 3)

There is no string macro in PythonCall for this, you need to use @pyexec and @pyeval.

The direct equivalent of your code is:

using PythonCall

@pyexec """
global add
def add(a, b):
  return a + b
"""

@pyeval("add")(2, 3)

Although a bit more idiomatic (and efficient) is:

using PythonCall

@pyexec """
def add(a, b):
  return a + b
""" => add

add(2, 3)

The reason for having macros instead of string macros is that it lets us have this nice => syntax for inputs and outputs, which you can’t do with PyCall. In turn this means the code can be executed in local scope (because we can extract the desired result before the scope is destroyed), so you don’t clutter global scope.

1 Like

thanks, is there a way to enable the python syntax highlight inside @pyexec "..." in VSCode? Like the py"..." does?

And, does it support multiple return, like:

@pyexec """
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b
""" => add, subtract

I don’t think syntax highlighting these is currently possible but it would be nice to have. This is where it is done for py"""... if you want to tackle it: julia-vscode/syntaxes/julia_vscode.json at 4b61fb2e3635d98f852de851bdb477e5bd082930 · julia-vscode/julia-vscode · GitHub

And yes, multiple inputs and outputs are supported, see the docstring.

(post deleted by author)

Too hard to use, removed it and switched back to PyCall. Maybe PythonCall is newer and does complex things better, the problem is it fails to do basic things well.

Can you be more specific about what you don’t like about PythonCall?