You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python同目录模块调用问题:兼顾便捷导入与内部引用

Solution for Intra-Package Imports While Keeping Convenient External Access

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 resolves alex to the outer alex folder (not the sub-package), which doesn't expose the CDE attribute.
  • Using import commons as AC fails because Python looks for commons in your system's sys.path, not in the same sub-package as KnowledgeBase.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:

  1. 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")
    
  2. Inside KnowledgeBase.py:
    You can use CDE and TimePeriod directly 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 13:02:30