0

I have the following data structure:

project/
    folder_a/
        file.py
    folder_b/
        useful_functions.py

I am running my file.py and attempting to import a set of functions I have written within useful_functions.py.

At first I tried the following:

from ..folder_b.useful_functions import function_a

But got the following error:

ValueError: attempted relative import beyond top-level package

I then removed the two dots at the beginning of the import statement which initially worked. I have since revisited this project with no changes and I am faced with a new error message. The following code:

from folder_b.useful_functions import function_a

Gives me the following error message:

ModuleNotFoundError: No module named 'folder_b'

I find it very strange that one time it works and later with no changes the import fails. I really would like to solve this with relative imports as I would like the code to work other machines with different absolute file paths.

Thanks in advance.

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
  • From which path are you running the file? – arabinelli May 16 '20 at 15:05
  • How are you running this file? – Mr_and_Mrs_D May 17 '20 at 10:33
  • I am running the file from within spyder 4. I have found a workaround with the following post by appending the cwd (in this case folder a) to the sys path. I'm surprised this is necessary, I'm sure there must be a simpler way. (https://stackoverflow.com/questions/8663076/python-best-way-to-add-to-sys-path-relative-to-the-current-running-script) – Matt_Haythornthwaite May 17 '20 at 15:15

1 Answers1

0

Well for the trillionth time running a script directly inside a package is considered an antipattern. I do not know how spyder runs stuff but presumably does

python file.py # from inside folder_a

This should be changed to

python -m folder_a.file # from inside project

This would resolve relative imports among packages inside project folder alright and will not need any sys.path or PYTHONPATH hacks

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361