0

So, I have a file called 'function.py' which includes the simple function:

def square(x):
  return x*x

I have a second bit of code like this:

from test import square
print(square(2))

If I store the second bit of code in a python file and run it in the terminal it works and gives the expected answer.

However, if I add a Python chunk in a Rmarkdown document like this:

```{python}
from test import square
print(square(2))
```

I get the error:

"Traceback (most recent call last): File "/var/folders/g7/462tmml173nfzj0j8437t9_m0000gn/T/RtmptMA22N/chunk-code-48764cec023f.txt", line 1, in from test import square ImportError: cannot import name square"

The Rmarkdown file and the python file are in the same directory. Answers about the specific error message are about dependencies, but I don't see how that's relevant in my case?

I've searched the web and read documentation, but I think I am missing something important. Thank you for the help!

Edit: Solved by specifically changing the path to the current working directory.

import sys, os
sys.path.append(os.getcwd())
import test
print(test.square(2))
D. de Jonge
  • 103
  • 7
  • Have you read and tried the solutions detailed in [this GitHub issue thread?](https://github.com/rstudio/reticulate/issues/108) – Mihai Chelaru Nov 14 '18 at 13:08
  • Is test a folder ? – Hcetipe Nov 14 '18 at 13:11
  • 1) The GitHub issue thread: yes, I have read this. The reticulate function that is given as solution is meant to be used in a R chunk, whereas I want to import within a Python chunk. The other solution of using "sys.path.append(os.path.join(os.path.dirname(__file__)))" is not quite clear to me; not sure how to implement it. 2) test is not a folder, test.py is a file with the function – D. de Jonge Nov 14 '18 at 13:39
  • You can try to put your test.py in a folder and then import like this : from yourfolder.test import * – Hcetipe Nov 14 '18 at 13:47
  • This solution does not work unfortunately. Am I missing something about what a module is exactly? Or am I missing something about how to define the location of the directory/file/function? – D. de Jonge Nov 14 '18 at 13:58
  • Solved! I have used sys.path.append(os.getcwd()) – D. de Jonge Nov 14 '18 at 14:09

1 Answers1

0

Solved by specifically changing the path to the current working directory.

import sys, os
sys.path.append(os.getcwd())
import test
print(test.square(2))

Answer was based on Python: Best way to add to sys.path relative to the current running script.

D. de Jonge
  • 103
  • 7