如何从祖父级兄弟目录导入Python类?PyCharm导入失败求解
Alright, let's break this down and get that import working properly—Python's relative imports can be tricky, but there are clean, idiomatic ways to solve this.
First, let's clarify your directory structure to make sure we're on the same page (it looks like there's a bit of repetition in your original listing):
project/ └── src/ ├── module_1/ │ ├── __init__.py # Make sure this exists (even if empty) │ └── module_1/ │ ├── __init__.py │ └── interesting.py └── module_2/ ├── __init__.py # Same here └── module_2/ └── importhere.py
The Most Idiomatic Solutions (PEP8 Compliant)
1. Use Absolute Imports (Recommended)
PEP8 strongly recommends absolute imports for readability and clarity, especially in larger projects. To make this work:
- First, mark the
srcdirectory as a Sources Root in PyCharm: Right-clicksrc→Mark Directory as→Sources Root. This tells PyCharm to treatsrcas the top-level package directory. - Then, in
importhere.py, use an absolute import path pointing to yourinteresting.pymodule:from module_1.module_1.interesting import YourClassName # Replace with your actual class name
If you're running the script from the command line (not just PyCharm), you'll need to ensure the project directory is in your PYTHONPATH. You can do this temporarily by running:
# From the project directory export PYTHONPATH=$(pwd) python src/module_2/module_2/importhere.py
2. Use Relative Imports (Only If Running as a Module)
Relative imports work when you're running your code as part of a package (not as a standalone script). Here's how:
- In
importhere.py, use relative dots to navigate up the directory tree. Sinceimporthere.pylives inmodule_2/module_2, we need to go up two levels to reach thesrcdirectory, then down tomodule_1/module_1:from ...module_1.module_1.interesting import YourClassName - To run this without errors, you cannot directly execute
importhere.py. Instead, run it as a module from theprojectdirectory:python -m src.module_2.module_2.importhere
3. Turn Your Project Into an Installable Package (Best for Long-Term Projects)
This is the most professional approach, as it aligns with Python's packaging standards. Create a pyproject.toml file in your project directory (or a setup.py if you prefer older tools) to define your package. Here's a minimal pyproject.toml:
[build-system] requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta" [project] name = "your-project-name" version = "0.1.0" packages = ["src.module_1", "src.module_2"]
Then install your package in editable mode (so changes are reflected immediately):
pip install -e .
Now you can import your class from anywhere in your code (or even outside the project) using the absolute import path:
from src.module_1.module_1.interesting import YourClassName
Why PyCharm Was Blocking the Import
PyCharm relies on recognizing your project's source roots to resolve imports correctly. If src wasn't marked as a Sources Root, PyCharm couldn't find the module_1 package relative to importhere.py. Once you mark src as a Sources Root, PyCharm will stop flagging the import as an error and even offer auto-completion.
Hope that clears up your confusion—let me know if you need help with any of these steps!
内容的提问来源于stack exchange,提问作者Jen Bates

