1

I am having problems with loading modules in a python script which I am calling via reticulate.

My file-structure basically looks like this:

Rscript.R

library(reticulate)
py_run_file("python1.py")
python1.py

print("test1")
import python2 as p2
p2.run_test(123)
python2.py

def run_test(x):
    print("inside p2-run_test()")
    print(x)

Now if I am running Rscript.R, it works fine, but changing python2.py like this (adding a new function):

python2.py

def run_test(x):
    print("inside p2-run_test()")
    print(x)

def run_test2(x):
    print("inside p2-run_test2()")
    print(x)

and python1.py like this (calling said function):

python1.py

print("test1")
import python2 as p2
p2.run_test2(123)

i get the following error:

test1
Error in py_run_file_impl(file, local, convert) : 
  AttributeError: 'module' object has no attribute 'run_test2'

Can anybody help me here how I can fix this?

Tej
  • 86
  • 5
Alex
  • 151
  • 12
  • Edit: If i change `python1.py` file like this: `[...] import python2 [...]` (so leaving out the local naming for the module) it works fine, however I do want to keep things organized inside my scripts, so that I know if a function is from a different file. – Alex Sep 17 '19 at 12:06
  • Can't reproduce. I don't receive any error. – nicola Sep 17 '19 at 12:13
  • Ok this is strange, but I found out how you can: If you add a new function to `python2.py` called `run_test1(x)` ,which does the same and try to call it in `python1.py` you should get this error – Alex Sep 17 '19 at 12:44
  • No error even with the edit. Please, edit your question with the minimal information to reproduce the error. Does the first setup give you an error? If not, remove it from the question and leave only the relevant information. – nicola Sep 17 '19 at 12:55
  • the error only appears if you run the R script in between adding the new function to `python2.py`. Maybe you missed that? – Alex Sep 17 '19 at 13:01
  • You then want to reload a python module after an edit. See here: https://stackoverflow.com/questions/4111640/how-to-reimport-module-to-python-then-code-be-changed-after-import. I'm going to close the question as dupe if you agree. This has anything to do with R and `reticulate`, by the way. – nicola Sep 17 '19 at 13:03

1 Answers1

0

As nicola said in the comments, this can be fixed by reloading the imported module:

You then want to reload a python module after an edit. See here: how to "reimport" module to python then code be changed after import

That fixed it for me.

Alex
  • 151
  • 12