模块重新加载的isinstance行为 [英] isinstance behavior with module reload

查看:86
本文介绍了模块重新加载的isinstance行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下两个.py文件:

Given the following two .py files:

aclass.py

aclass.py

class A(object):
    pass

main.py

def importer(klass):
    """
    Used to import classes from there python qalname
    """
    import_ = lambda m, k: getattr(__import__(m, fromlist=k), k)
    klass = klass.split('.')
    module = '.'.join(klass[:-1])
    klass = klass[-1]
    return import_(module, klass)

from aclass import A

import_A = importer('aclass.A')
print isinstance(A(), import_A)  # Expected to be true 
print isinstance(import_A(), A)  # Expected to be true 

在这个阶段,一切正常(我的程序打印 True\\\
True

但是如果我修改 importer 方法来强制重新加载,即:

At this stage, everything works fine (my program prints True\nTrue) But if I modify the importer method to enforce a reload, ie:

这一行:

    import_ = lambda m, k: getattr(__import__(m, fromlist=k), k)

被替换为:

    import_ = lambda m, k: getattr(reload(__import__(m, fromlist=k)), k)

我的程序返回

False
False

我不明白这种行为。

推荐答案

重新加载模块意味着重新执行其内容,在本例中为 A类(对象):传递 。所以它创造了另一个不同的类。它的行为与以下相同:

Reloading a module means re-executing its content, in this case class A(object): pass. So it creates another different class. It's the same behavior as:

class A(object):
    pass
a = A()
class A(object):          # a different class
    pass
print isinstance(a, A)    # False

这应该足以解释为什么裸 reload()通常是个坏主意。我相信其他人可以指出实现更复杂的重新加载程序的框架,例如修补旧类被认为等于新类。

This should be enough to explain why a bare reload() is usually a bad idea. I'm sure others could point to frameworks that implement more sophisticated reloading procedures, e.g. patching the old class to be considered equal to the new one.

这篇关于模块重新加载的isinstance行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆