简体   繁体   English

模块重新加载时的isinstance行为

[英]isinstance behavior with module reload

Given the following two .py files: 给定以下两个.py文件:

aclass.py aclass.py

class A(object):
    pass

main.py 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 

At this stage, everything works fine (my program prints True\\nTrue ) But if I modify the importer method to enforce a reload, ie: 在此阶段,一切正常(我的程序显示True\\nTrue ),但是如果我修改importer方法以强制重新加载,即:

this line: 这行:

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

is replaced by: 替换为:

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

my programs returns 我的程序返回

False
False

And I do not understand this behavior. 而且我不了解这种行为。

Reloading a module means re-executing its content, in this case class A(object): pass . 重新加载模块意味着重新执行其内容,在本例中为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

This should be enough to explain why a bare reload() is usually a bad idea. 这应该足以解释为什么裸露的reload()通常不是一个好主意。 I'm sure others could point to frameworks that implement more sophisticated reloading procedures, eg patching the old class to be considered equal to the new one. 我确信其他人可以指向实现更复杂的重装过程的框架,例如,修补旧类以使其与新类相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM