简体   繁体   中英

Relative import from top-level package

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, eg 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM