0

I have this structure

proj
 utils.py
    |- sub1
        file1.py
    |- sub2
        file2.py
 ...

utils.py is a module containing a bunch of useful functions. I want them to be accessible in every filesX.py in the subdirectories, e.g. via utils.func1()...

Therefor I want to import utils from file1.py via from .. import utils, but I get a

ValueError: attempted relative import beyond top-level package

error.

Is there a clean way to do so without adding absolute paths and without editing the PYTHONPATH?

RolleRugu
  • 233
  • 2
  • 11
  • Possible duplicate of [Unable to import module from another package](https://stackoverflow.com/questions/54604493/unable-to-import-module-from-another-package) – Johnny Feb 13 '19 at 13:21
  • See this https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time for a detailed description of how relative imports work – fstop_22 Feb 13 '19 at 13:21
  • Possible duplicate of [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Laurent LAPORTE Feb 13 '19 at 13:23

1 Answers1

0

try this:

from proj import utils

My opinion is that this is how to solve this problem, if you dont want to edit eny Environment variable.

Using absolute imports means that it doesn’t matter where in the project a module is when you try to import another module. Python will always look up the module to import from the root of your package.

ncica
  • 7,015
  • 1
  • 15
  • 37