Python同目录模块调用问题:兼顾便捷导入与内部引用
Let's break down how to fix your import issues while keeping the handy import alex as al workflow for test.py:
The Root Cause of Your Errors
Your problems stem from incorrect import paths inside KnowledgeBase.py:
- When you use
import alex as al, Python likely resolvesalexto the outeralexfolder (not the sub-package), which doesn't expose theCDEattribute. - Using
import commons as ACfails because Python looks forcommonsin your system'ssys.path, not in the same sub-package asKnowledgeBase.py.
Fix 1: Use Relative Imports for Intra-Package References
This is the cleanest approach for modules within the same package. Update KnowledgeBase.py to use relative imports to pull in content from commons.py:
# KnowledgeBase.py from .commons import CDE, TimePeriod class KnowledgeBase: def __init__(self): # Now you can use CDE and TimePeriod directly self.sample_cde = CDE(name="test", value=123) self.sample_period = TimePeriod(start="2024-01-01", end="2024-12-31")
The . in from .commons tells Python to look in the same directory as KnowledgeBase.py for the commons module.
Fix 2: Absolute Imports (Alternative)
If you prefer absolute paths, make sure your project root (the parent folder of the outer alex directory) is in Python's sys.path, then use the full package path:
# KnowledgeBase.py from alex.commons import CDE, TimePeriod class KnowledgeBase: # ... rest of your code
Keep Your Convenient External Import
Your existing __init__.py setup is perfect for letting test.py use import alex as al to access all exposed objects. Leave it as-is:
# __init__.py from .KnowledgeBase import KnowledgeBase from .commons import *
Verify the Workflow
Now both scenarios work seamlessly:
In test.py:
import alex as al # Access your classes/objects directly kb = al.KnowledgeBase() new_cde = al.CDE(name="example", value=456) new_period = al.TimePeriod(start="2024-02-01", end="2024-02-29")Inside KnowledgeBase.py:
You can useCDEandTimePerioddirectly without any import errors.
Pro Tip for Running the Code
When executing test.py, run it from your project root directory (the parent of the outer alex folder) using:
python -m alex.test
This ensures Python correctly recognizes the package structure and avoids path-related bugs.
内容的提问来源于stack exchange,提问作者pierre_j

