简体   繁体   中英

Importing a module from a parent package

I have this directory structure

src
|
|\Lib
| |__init__.py
| |utils.py
|  \Scripts
|   |__init__.py
|   |myscript.py
|__init__.py

and I need to import utils.py in myscript.py but from..utils import function is giving me

ImportError: attempted relative import with no known parent package

so my attempt is to add the parent package to the path by doing

import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parents[1]))

inside the innermost __init__.py (under the Scripts folder) without any success.

What am I missing here?

My suggestion to have a good understanding of how to deal with this kind of problem is to read this post: Relative imports for the billionth time

One solution to your problem could be the following:

  1. Have this folder structure
src
|
|\Lib
| |__init__.py
| |utils.py
|  
|\Scripts
| |myscript.py
  1. Keep this in your myscript.py
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parents[1]))

and change from..utils import function to from Lib.utils import function

This is one way to solve it.

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