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:
JavaScript
x
5
1
>library(reticulate)
2
>foo <- import("foo")
3
>res <- foo.func()
4
<generator object at 0x7fd4fe98ee40>
5
Advertisement
Answer
You could use iterate
or iter_next
.
As an example, consider a python generator firstn.py
:
JavaScript
1
6
1
def firstn(n):
2
num = 0
3
while num < n:
4
yield num
5
num += 1
6
You can traverse the generator either with iterate
:
JavaScript
1
10
10
1
library(reticulate)
2
source_python('firstn.py')
3
gen <- firstn(10)
4
gen
5
#<generator object firstn at 0x0000020CE536AF10>
6
7
result <- iterate(gen)
8
result
9
# [1] 0 1 2 3 4 5 6 7 8 9
10
or with iter_next
:
JavaScript
1
7
1
iter_next(gen)
2
[1] 0
3
iter_next(gen)
4
[1] 1
5
iter_next(gen)
6
[1] 2
7