在Python中替换包装包装包装

发布于 2025-02-12 12:56:11 字数 1446 浏览 0 评论 0原文

我试图用自定义软件包替换dateTime软件包软件包软件包(extensions.dateTime.dateTime ),看起来如下:

from datetime import *

class date(date):
    @property
    def test(self):
        print("test")

为了确保使用我的软件包,我从sys.modules中替换了我的sys.modules扩展软件包(编辑:修补<代码> dateTime 在导入calendarweek)之前:

import datetime as _datetime
import extensions.datetime
sys.modules[_datetime.__name__] = extensions.datetime

import calendarweek as _calendarweek
import extensions.calendarweek
sys.modules[_calendarweek.__name__] = extensions.calendarweek

但是,当我运行calendarweekweek.calendarweek()[0]时。 __ class __我希望它是extensions.dateTime.date,但是它是dateTime.date.date。我尝试使用ementlib.reload()尝试重新加载两个模块。 我在main.py中运行这些命令,该命令与Extensions软件包处于相同的目录级别:

# noinspection PyUnresolvedReferences
import extensions  # importing the extensions-package first to make sure only they're replacement is taking effect

from extensions.calendarweek import CalendarWeek

def main():
    CalendarWeek()[0].__class__

if __name__ == "__main__":
    main()

我如何替换使用内置dateTime的使用软件包在全球范围内,以便每次尝试使用内置的软件包点指向我的自定义实现?

谢谢!

I'm trying to replace the use of the datetime package inside the calendarweek package with a custom package that adds additional functionality to it (extensions.datetime), which looks as follows:

from datetime import *

class date(date):
    @property
    def test(self):
        print("test")

To make sure that my package is used I replaced the module reference in sys.modules from the __init__.py inside my extensions package (EDIT: patching datetime before importing calendarweek):

import datetime as _datetime
import extensions.datetime
sys.modules[_datetime.__name__] = extensions.datetime

import calendarweek as _calendarweek
import extensions.calendarweek
sys.modules[_calendarweek.__name__] = extensions.calendarweek

However, when I run calendarweek.CalendarWeek()[0].__class__ I would expect it to be extensions.datetime.date, however it's datetime.date. I tried reloading both modules using importlib.reload().
I run those commands inside a main.py, which is at the same directory-level as the extensions package:

# noinspection PyUnresolvedReferences
import extensions  # importing the extensions-package first to make sure only they're replacement is taking effect

from extensions.calendarweek import CalendarWeek

def main():
    CalendarWeek()[0].__class__

if __name__ == "__main__":
    main()

How do I replace the use of the builtin datetime package, globally, so that every tried use of the builtin package points to my customized implementation?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文