Can R variables be passed to py_run_string in reticulate package?

I was wondering if there is a way to pass R variables into py_run_string in reticulate? I saw that it is easy to do in RMarkdown using the notation r.variablename. But I was also interested in knowing whether that is possible when working directly in a R script instead of Rmarkdown. I have listed below example code to illustrate what I am trying to do.

py_run_string("x = 10")

py$x # gives the value 10

# for passing a R variable into python, currently I define a function
py_run_string("
def getsquare(y):
    return y**2
              ")

y  = 10
py$getsquare(y) # gives the value 100

# My question is whether there is an easier way to pass y into py_run_string something like
py_run_string("r.y**2") 

I would appreciate any pointers on this.

I am apprehensive about interpolating into strings then executing the result, due to the possibility of injection attacks.

Assuming that you are managing this risk, you might consider the glue package.

library("reticulate")
library("glue")

y = 10

py_run_string(glue("print({y}**2)"))
1 Like

Thanks very much for your suggestion and the note of caution on using this. I was not familiar with glue package. Seems like a good one to know for other tasks also.

1 Like