rstudio / reticulate

R Interface to Python
https://rstudio.github.io/reticulate
Apache License 2.0
1.67k stars 327 forks source link

repl_python: how to parse funciton in Rstudio? #433

Open MatthieuStigler opened 5 years ago

MatthieuStigler commented 5 years ago

I am trying to run a python code with a custom-defined function, but running into parsing errors in Rstudio?

Also, is there any chance Rstudio would do the indentation correctly within a function? If type "new line", will have 2 spaces instead of the four required?

Thanks!

Try:

library(reticulate)
use_condaenv("py2", conda ='/home/matifou/Programs/anaconda2/bin/conda', required = TRUE)

repl_python()
def helloworld(x):
    print("Hello World "+x)
    print("Hello World again "+x)

helloworld("you")
exit
jstatwick commented 5 years ago

To both answer and piggyback off this...

That is not really the intended function of repl_python(). This function is intended for interactive line-by-line coding in the console, rather than use in a programming context. You want the following:

library(reticulate)
use_condaenv("py2", conda ='/home/matifou/Programs/anaconda2/bin/conda', required = TRUE)

py_run_string('
def helloworld(x):
    print("Hello World "+x)
    print("Hello World again "+x)

helloworld("you")
')

That said, reticulate could and should have the ability to operate as @MatthieuStigler proposed. Essentially, you should be able to call a temporary python_chunk() within R. Such functionality would bridge the gap between functions that are a little too large or complex (maybe contain both single and double quotes?) for py_run_string() to be practical, and a little too small or single-use for source_python() to make sense. This functionality is already present in Rmarkdowns via intermingled R and python chunks, but there isn't the equivalent functionality for r scripts (including, for example, shiny apps, where this would be potentially the most useful).