rPython and __future__ imports

843 Views Asked by At

My python script starts with

from __future__ import division

In R I do

library(rPython)
python.load("myscript.py")

I get

File "", line 2 SyntaxError: from future imports must occur at the beginning of the file

1

There are 1 best solutions below

0
On

I just bumped into the same problem - apparently python.load() is simply executing the script loaded from the location as if it were a bunch of commands.

I'm not sure if it's wrapped or preceded with some boilerplate code by default somehow, but it seems so. And if you were to catch errors using rPython it would surely be executed within a try... block (given the current code on GitHub at least).

However, using a workaround based on execfile() did the job for me:

python.exec("execfile('myscript.py')")

Another approach is, if there's no need to execute code in the main block, to import the module

python.exec("import myscript")

however, in this slightly more convoluted case, you likely have to deal with path problems, as mentioned e.g. here.

(It would probably be a good idea to let the package maintainers know about this situation, and that it could use something better than a workaround.)