Python从上级子包导入函数遇ModuleNotFoundError问题排查
Hey Johnny, let's walk through why you're hitting this error—this is a super common gotcha when setting up Python packages, and I’ve sorted out this exact problem more times than I can count. Here are the most likely culprits and fixes:
1. You’re Missing __init__.py Files
Python requires every directory you want to treat as a package to have an __init__.py file (it can be completely empty, no code needed!). If your directory structure looks like this:
my_project/ ├── package/ │ └── target_module.py # Has your function └── my_script.py
You need to add an empty __init__.py inside the package folder. Without it, Python doesn’t recognize that directory as a valid package to import from.
2. Your Parent Directory Isn’t in Python’s Search Path
Even with __init__.py, Python can’t find the package if its parent folder isn’t in sys.path (the list of directories Python checks for modules). To fix this, add these lines at the very top of my_script.py:
import sys from pathlib import Path # Add the parent directory (where "package" lives) to sys.path sys.path.append(str(Path(__file__).parent))
This dynamically adds the directory containing package to Python’s search scope, so it can locate the module you want.
3. You’re Running the Script the Wrong Way
If your project has a nested structure (e.g., src/package/ and src/my_script.py), running python my_script.py directly from the src folder can confuse Python’s module system. Instead, run the script as a module from your project’s root directory:
python -m src.my_script
This tells Python to treat src as part of the module hierarchy, making it easier to import from sibling/parent packages correctly.
4. There’s a Naming Conflict
Double-check that there isn’t a file or module with the same name as your package in the same directory as my_script.py. For example, if you have a package.py file next to my_script.py, Python will try to import that file instead of the parent directory’s package, causing the error.
Start with checking the __init__.py first—it’s the easiest fix, and 9 times out of 10 that’s the issue. If that doesn’t work, move through the other steps one by one.
内容的提问来源于stack exchange,提问作者Johnny Metz

