2
votes

Apologies if this has already been answered, but I'm having a surprisingly hard time using the "py" string macro included with the PyCall library when I feed it a variable representing a string instead of a simple string.

Examples:

@py_str "2 + 2" 

returns 4

z = "2 + 2"
@py_str z

causes a error that interpolate_pycode does not take an Expr argument, as does @py_str ($(z)).

How can I pass @py_str a string variable?

(Just to clarify - above was a toy example, I'm using it for an application where it really is necessary).

1
Isn't it just py""" """ (i.e. Without the _str)? - daycaster

1 Answers

2
votes

@py_str "\$\$z" is your friend (looked at macro help using ?@py_str in REPL). Better to write the same macro as py"$$z"

From the REPL help (bolded relevant part):

py".....python code....."

Evaluate the given Python code string in the main Python module.

If the string is a single line (no newlines), then the Python expression is evaluated and the result is returned. If the string is
multiple lines (contains a newline), then the Python code is compiled and evaluated in the main Python module and nothing is returned.

If the o option is appended to the string, as in py"..."o, then the return value is an unconverted PyObject; otherwise, it is
automatically converted to a native Julia type if possible.

Any $var or $(expr) expressions that appear in the Python code (except in comments or string literals) are evaluated in Julia and passed to Python via auto-generated global variables. This allows you to "interpolate" Julia values into Python code.

Similarly, ny $$var or $$(expr) expressions in the Python code are evaluated in Julia, converted to strings via string, and are pasted
into the Python code. This allows you to evaluate code where the code itself is generated by a Julia expression.

PS the little typo ny instead of any is in the package source.