英文:
What are best practices to change a Python module's name while keeping backwards compatibility?
问题
有一个Python模块,被其他不同的人使用。如果我决定模块的名称需要更改(不一定是一个好主意,让我们假设已经做出了需要重命名的决定)。
是否有一种规范的方式来确保用户仍然可以使用旧名称,以便import newname; newname.foo()
和import oldname; oldname.foo()
都能正常工作并调用相同的底层代码?
英文:
I wrote a Python module used by various other people. If I decide that the module's name should change (not saying this is necessarily a good idea, let's just assume that a decision was made that it needs to be renamed).
Is there a canonical way to ensure that users can still use the old name, so that both import newname; newname.foo()
and import oldname; oldname.foo()
work and invoke the same underlying code?
答案1
得分: 2
这不是官方的方式,但是这是一个头脑风暴的想法。
您可以创建一个新的Python模块,作为一个包装器,并从旧模块中简单地导入所有内容。然后用户可以从这个新模块导入,它会将所有请求转发到原始模块。
# wrapper_module.py
from oldname import *
使用这种方法,用户现在可以使用新名称导入模块:
import wrapper_module as newname
他们仍然可以使用旧名称访问函数和类:
import oldname
# 这两者都将起作用并调用相同的底层代码:
newname.foo()
oldname.foo()
使用这种方法将有助于在逐渐过渡到新模块名称的同时保持向后兼容性。
英文:
It is not the canonical way, but it is a brainstorming idea.
You can create a new Python module that serves as a wrapper and simply imports everything from the old module. Users can then import from this new module, and it will forward all requests to the original module.
# wrapper_module.py
from oldname import *
With this approach, users can now import the module using the new name:
import wrapper_module as newname
And they can still access the functions and classes using the old name:
import oldname
# Both of these will work and call the same underlying code:
newname.foo()
oldname.foo()
Using this will help maintain backward compatibility while allowing you to transition to the new module name gradually.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论