如何在不修改依赖代码的情况下迁移Python模块并保持原有导入路径有效
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 foowill no longer throw aModuleNotFoundError—it'll correctly pull thefooconstant from the relocatedbar.py.
This approach keeps all existing dependent code working without any modifications, exactly what you need!
内容的提问来源于stack exchange,提问作者ikamen

