遍历Python对象树

发布于 2024-07-27 22:22:51 字数 933 浏览 1 评论 0原文

我正在尝试在 Python 中实现动态重新加载对象,以实时反映代码更改。

模块重新加载正在工作,但我必须重新创建模块类的每个实例才能使更改生效。

问题是对象数据(对象 __dict__ 内容)在此过程中丢失。

所以我尝试了另一种方法:

def refresh(obj, memo=None):
    if memo is None:
        memo = {}
    d = id(obj)
    if d in memo:
        return
    memo[d] = None
    try:
        obj.__class__ = getattr(sys.modules[obj.__class__.__module__], 
                obj.__class__.__name__)
    except TypeError:
        return
    for item in obj.__dict__.itervalues():
        if isinstance(item, dict):
            for k, v in item.iteritems():
                refresh(k, memo)
                refresh(v, memo)
        elif isinstance(item, (list, tuple)):
            for v in item:
                refresh(v, memo)
        else:
            refresh(item, memo)

令人惊讶的是它有效! 在我的对象上调用refresh()后,新代码就会生效,无需重新创建它们。

但我不确定这是否是遍历对象的正确方法? 有没有更好的方法来遍历对象的组件?

I'm trying to implement dynamic reloading objects in Python, that reflect code changes live.

Modules reloading is working, but I have to recreate every instance of the modules' classes for changes to become effective.

The problem is that objects data (objects __dict__ content) is lost during the process.

So I tried another approach:

def refresh(obj, memo=None):
    if memo is None:
        memo = {}
    d = id(obj)
    if d in memo:
        return
    memo[d] = None
    try:
        obj.__class__ = getattr(sys.modules[obj.__class__.__module__], 
                obj.__class__.__name__)
    except TypeError:
        return
    for item in obj.__dict__.itervalues():
        if isinstance(item, dict):
            for k, v in item.iteritems():
                refresh(k, memo)
                refresh(v, memo)
        elif isinstance(item, (list, tuple)):
            for v in item:
                refresh(v, memo)
        else:
            refresh(item, memo)

And surprisingly it works ! After calling refresh() on my objects, the new code becomes effective, without need to recreate them.

But I'm not sure if this is the correct way to traverse an object ? Is there a better way to traverse an object's components ?

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

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

发布评论

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

评论(1

青春如此纠结 2024-08-03 22:22:51

请参阅 Python Cookbook 中的此食谱(或者可能更好的是“打印”中的版本)一本,我相信你实际上可以通过谷歌图书搜索免费阅读,或者肯定可以在 O'Reilly 的“Safari”网站上使用免费的 1 周试用订阅来阅读 - 我对 Hudson 的原始食谱进行了大量编辑以获得“印刷书”版本!)。

See this recipe in the Python Cookbook (or maybe even better its version in the "printed" one, which I believe you can actually read for free with google book search, or for sure on O'Reilly's "Safari" site using a free 1-week trial subscription -- I did a lot of editing on Hudson's original recipe to get the "printed book" version!).

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