1

I use Python from RStudio with the reticulate package. Is it possible to create custom modules and import them just as in normal Python? Here's a MWE:

My custom module is stored in a file called test_class.py and defines the Test class:

class Test:
  
  def __init__(self, name):
    self.name = name

My main file main.py is in the same directory as test_class.py and contains

from test_class import Test

x = Test("Bobby")
print(x.name)

If I run the main file within RStudio using reticulate, it fails with: ModuleNotFoundError: No module named 'test_class'. If I run it in the terminal with python (python main.py) it works perfectly. How can I get that behavior in RStudio?

Ben
  • 429
  • 4
  • 11

2 Answers2

0

I found the culprit: reticulate looks into the project directory for import statements, not in the directory of the python file making the import. So you need to adjust the path in your import statement.

Ben
  • 429
  • 4
  • 11
0

Just so this is here. I think this is what @Ben did

require(reticulate)
test <- import_from_path(module = "test_class",path="path/to/file")

can also try (see answer: from import from python in reticulate)

require(reticulate)
test <- import_from_path(module = "test_class",path="path/to/file")$Test
jtclaypool
  • 131
  • 1
  • 5