将代码移出 __init__.py 但保持向后兼容性
我正在开发一个 Python 项目,以前的开发人员将大部分代码放在基本 __init__.py
文件中。我希望能够将代码从文件移到子目录中的新文件中。
spam/
__init__.py
foobar/
__init__.py
eggs.py
因此导入垃圾邮件模块将使用 foobar/eggs.py 中的代码。
我想保持100%的兼容性,因为当前实现垃圾邮件的代码无法更改。
I'm working on a Python project where a previous developer placed a large portion of the code in the base __init__.py
file. I would like to be able to move code out of the file to a new file in a subdirectory.
spam/
__init__.py
foobar/
__init__.py
eggs.py
So importing the spam module would use the code in foobar/eggs.py.
I would like to keep 100% compatibility because the code that current implements spam can't be changed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
100% 兼容性可能是不可能的。有些东西(比如 pickle)确实关心某些东西的定义位置。
您可以通过导入 __init__.py 文件中的类/函数来获得大部分兼容性。
100% compatibility is probably not possible. A few things (like pickle) really care about where something is defined.
You can get most of the compatibility by importing the classses/functions in the
__init__.py
file.在 spam/__init__.py 中添加
from foobar import *
应该足以使所有内容都处于与之前相同的范围内。或者,如果您需要更改名称或限制导出的内容,则可以在同一文件中重新定义需要导出的所有内容,例如 foo = foobar.newfoo。当然,这留下了让所有内容仍然在全局范围内的问题,但是如果您需要它在外部看起来相同,那么您对此无能为力。
Adding
from foobar import *
in spam/__init__.py should be sufficient to get everything in the same scope that it was in before. Alternately, you can redefine everything that you need exported in the same file, such asfoo = foobar.newfoo
if you have any need to change names or restrict what's exported.Of course, that leaves the problem of having everything still in the global scope, but you can't do much about that if you need it to look identical externally.
在垃圾邮件的 __init__.py 中,您可以将 foobar.egg 内容作为本地导入,然后从垃圾邮件导入它的任何人仍然可以访问它,
您也可以在垃圾邮件 __init__.py 中编写包装函数,它只需调用 Egg 等效项即可扩展兼容性具体案例
in spam's __init__.py, you can import foobar.egg stuff as local, then anyone importing it from spam will still have access to it
you can also write wrapper functions in in spam __init__.py which simply call the eggs equivalent for extended compatibility in specific cases