Scott G
Scott G

Reputation: 2310

Spyder not handling relative imports

I am attempting to python3 proof my work and spyder seems to be having an issue with absolute_import.

For demonstration purposes I created two simple files. caller and callme

caller

from __future__ import absolute_import
from .callme import helloWorld

def runme(msg):
    helloWorld(msg)


if __name__ == "__main__":

    runme('It worked!')

callme

def helloWorld(msg):      
    print("helloWorld's message is '{}'".format(msg))


if __name__ == "__main__":

    helloWorld('Hi')

When attempting to run caller from spyder I get the following error:

ValueError: Attempted relative import in non-package

Running from ipython via the anaconda prompt (python 2) or from jupyter notebook (running python3 or python2) both work properly.

Ideas on how to fix spyder's behavior so it properly recognizes absolute_import?

Spyder versions tried:

Update

Updating spyder via conda update spyder (now version 3.3.2) did not fix the issue.

Upvotes: 0

Views: 1312

Answers (1)

Carlos Cordoba
Carlos Cordoba

Reputation: 34156

If you run python caller.py in a system terminal, you'll get exactly the same error as the one you posted, i.e.

ValueError: Attempted relative import in non-package

So this is not a problem with Spyder (because Spyder runs something similar to python caller.py when you execute a file with Run > Run), but with the way relative imports works.

Please see this answer for a proper explanation:

https://stackoverflow.com/a/11537218/438386

In essence, you can't use relative imports in scripts.


Note: There's a workaround to avoid this error, as described in this answer:

https://stackoverflow.com/a/11536794/438386

However, we don't have the ability to execute a script as a package in Spyder, sorry.

Upvotes: 1

Related Questions