1

I have an RMarkdown document with the following content:

```{r setup, include=FALSE}
library(reticulate)
```

```{r}
#These lines don't seem to make a difference, but I have seen them suggested elsewhere
reticulate::use_python('/usr/local/Cellar/python@3.8/3.8.6_2/bin/python3.8')
knitr::knit_engines$set(python = reticulate::eng_python)
```


```{r}
py <- reticulate::py
```


```{python}
import sys
sys.version

a = 1
```


```{r python from r}
print(py$a)
b <- 2
```

```{python r from python}
print(r.b)
```

If I run this in RStudio, either interactively or by knitting the whole document, everything works and the last chunk prints "2". However, when running from the R console through render (or my production script that performs regular model trainings) it fails on the last chunk with the following error:

Error in py_call_impl(callable, dots$args, dots$keywords) :
RuntimeError: Evaluation error: object 'b' not found.

Detailed traceback: File "", line 1, in File "/Library/Frameworks/R.framework/Versions/3.6/Resources/library/reticulate/python/rpytools/call.py", line 21, in python_function raise RuntimeError(res[kErrorKey])

Accessing Python variables from R seems to work properly, but I cannot access R variables in Python.

I am using Reticulate 1.18, Knitr 1.30, and rMarkdown 2.6. Calling py_config() from both RStudio and the R console returns the same result:

>py_config()

python: /usr/local/Cellar/python@3.8/3.8.6_2/bin/python3.8 libpython:
/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/config-3.8-darwin/libpython3.8.dylib pythonhome:
/usr/local/Cellar/python@3.8/3.8.6_2/Frameworks/Python.framework/Versions/3.8:/usr/local/Cellar/python@3.8/3.8.6_2/Frameworks/Python.framework/Versions/3.8 version: 3.8.6 (default, Nov 20 2020, 18:29:40) [Clang 12.0.0 (clang-1200.0.32.27)] numpy:
/usr/local/lib/python3.8/site-packages/numpy numpy_version: 1.18.5

NOTE: Python version was forced by RETICULATE_PYTHON

Phil
  • 7,287
  • 3
  • 36
  • 66
Jordan Bentley
  • 1,309
  • 1
  • 8
  • 28

2 Answers2

1

It looks like this is broken in the current version of Reticulate. I downgraded to 1.16 and that fixed it, 1.17 and later are broken. I've submitted a ticket to the devs: https://github.com/rstudio/reticulate/issues/914

Edit: This is now fixed in the latest dev version, which can be installed with remotes::install_github("rstudio/reticulate")

Jordan Bentley
  • 1,309
  • 1
  • 8
  • 28
0

It happened to me because I had the stupid idea to name an object r in a RMarkdown script

```{python}
import requests
r = requests.get('http://api.worldbank.org/v2/countries?incomeLevel=LMC')
r.content
```

will work in a python interpreter but might return an error in a RMarkdown document (because reticulate looks for the object content in python environment)

Best workaround: never naming an object r when using reticulate

linog
  • 5,786
  • 3
  • 14
  • 28