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

如何在不修改依赖代码的情况下迁移Python模块并保持原有导入路径有效

How to Maintain from proj.bar import foo Compatibility After Moving bar.py to a Subfolder

Got it, let's fix this problem. The issue with your initial approach is that importing bar as an attribute of the proj module doesn't make it visible as a submodule named proj.bar to Python's import system. Here's what you need to write in proj/__init__.py:

import sys
from .subfolder import bar

# Register the subfolder's bar module as proj.bar in Python's module registry
sys.modules['proj.bar'] = bar

# Optional: Add this line if you also want to support `from proj import foo`
from .subfolder.bar import foo

Why this works:

When Python processes from proj.bar import foo, it first checks sys.modules for a module named proj.bar. By explicitly assigning sys.modules['proj.bar'] = bar, we're telling Python that the proj.bar module is actually the one stored in your subfolder. This lets the import system resolve the old path to your new module location seamlessly.

Let's test it out:

  • Running import proj; print(proj.bar) will still show the correct module path (now pointing to ~/proj/subfolder/bar.py).
  • from proj.bar import foo will no longer throw a ModuleNotFoundError—it'll correctly pull the foo constant from the relocated bar.py.

This approach keeps all existing dependent code working without any modifications, exactly what you need!

内容的提问来源于stack exchange,提问作者ikamen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 02:42:38