将代码移出 __init__.py 但保持向后兼容性

发布于 2024-10-25 23:40:51 字数 274 浏览 3 评论 0原文

我正在开发一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一口甜 2024-11-01 23:40:55

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.

坏尐絯℡ 2024-11-01 23:40:55

在 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 as foo = 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.

很酷又爱笑 2024-11-01 23:40:55

在垃圾邮件的 __init__.py 中,您可以将 foobar.egg 内容作为本地导入,然后从垃圾邮件导入它的任何人仍然可以访问它,

from foobar.eggs import apples_newname as apples_oldname
# or (but import * isn't recommended except for extreme cases)
from foobar.eggs import *

您也可以在垃圾邮件 __init__.py 中编写包装函数,它只需调用 Egg 等效项即可扩展兼容性具体案例

import foobar.eggs
def apples_newname(*args, **kwargs):
    foobar.eggs.apples_oldname(*args, **kwargs)

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

from foobar.eggs import apples_newname as apples_oldname
# or (but import * isn't recommended except for extreme cases)
from foobar.eggs import *

you can also write wrapper functions in in spam __init__.py which simply call the eggs equivalent for extended compatibility in specific cases

import foobar.eggs
def apples_newname(*args, **kwargs):
    foobar.eggs.apples_oldname(*args, **kwargs)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文