Skip to content
Advertisement

Is there any way to call base python function in r using reticulate?

I got a “generator object” from a python function. However, I tried many ways but failed to read the “generator object” in r using reticulate. I know python base function list() can convert “generator object” to “json“, which I can then read in r. I wonder how to use base python function in r? (I would not prefer to use py_run_file)

For example:

>library(reticulate)
>foo <- import("foo")
>res <- foo.func()
<generator object at 0x7fd4fe98ee40>

Advertisement

Answer

You could use iterate or iter_next.

As an example, consider a python generator firstn.py:

def firstn(n):
  num = 0
  while num < n:
    yield num
    num += 1

You can traverse the generator either with iterate :

library(reticulate)
source_python('firstn.py')
gen <- firstn(10)
gen
#<generator object firstn at 0x0000020CE536AF10>

result <- iterate(gen)
result
# [1] 0 1 2 3 4 5 6 7 8 9

or with iter_next:

iter_next(gen)
[1] 0
iter_next(gen)
[1] 1
iter_next(gen)
[1] 2
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement