Unexpected output when using Python function in R chunk with reticulate
Python Chunk:
def print_address(address):
py_address = r.address
print(py_address)
R Chunk:
address <- list("1 Main Street", "2 Hope Street")
lapply(address, py$print_address)
Actual:
[[1]] NULL
[[2]] NULL
Expected:
[[1]] [1] "1 Main Street"
[[2]] [1] "2 Hope Street"
There are two parts to this :
1)The python function is expected to print . But the output of python console is not displayed . This looks like a typical flushing issue, which it is. https://github.com/rstudio/rstudio/issues/3271 So the address will be printed if we flush the stdout in Python.
import sys
def print_address(address):
py_address = address
print(py_address)
sys.stdout.flush()
2) Our python function does not return a value . I am not very sure how this works, but it seems in this case python returns a null
to R. This does not seem to be a problem if we call the function directly, but in an lapply
the returned null is added to list and implicitly gets printed. This will be printed even if you use stdout.flush
in python.