Search code examples
rreticulate

In R cannot get function from imported python file using reticulate


I would like to import a python file and then use a function within the python file; but it does not work (it only work for source_python). Is it suppose to be this way?

In python file called the_py_module.py includes this code:

def f1():
  return "f one"


def f2():
  return "f two"

R script

# Trying to import the python file, which appear to work:
reticulate::import("the_py_module")

Gives this output: Module(the_py_module)

# But when calling the function: 
f1()

I get error saying: Error in f1() : could not find function "f1"

This works using source python script though.

reticulate::source_python("the_py_module.py")
f1()

Solution

  • Try the following approach:

    > library(reticulate)
    > my_module <- import(the_py_module)
    > my_module$f1()
    [1] "f one"
    

    or, using your approach

    > my_module_2 <- reticulate::import("the_py_module")
    > my_module_2$f1()
    [1] "f one"