比较deepcopy中的Python对象

时间:2014-07-30 18:16:34

标签: python copy compare assert

有没有办法将Python对象与深度复制生成的对象进行比较?

e.g:

    import copy 

    original_object = SomeObject()
    cloned_object = copy.deepcopy(original_object)
    assertDeepCopy(original_object, cloned_object)

2 个答案:

答案 0 :(得分:1)

这就是我相信你的要求:

def deep_compare(left, right):
    try:
        if not left.__dict__:
            return left == right

        for key in left.__dict__:
            if key not in right.__dict__:
                return false
            else:
                return deep_compare(left[key], right[key])
    except (AttributeError, TypeError):
        return left == right 

但请注意,这可能会在很多地方出错:如果对象没有以您喜欢的方式定义==,您将无法获得所需的答案。

答案 1 :(得分:1)

我知道这是一个老答案,但是对于Python 3,以前的代码对我不起作用,因此我在此代码中对其进行了更新,对我更有效:


import logging
log = logging.getLogger(__name__)

...

    def deep_compare(self,left, right, level=0):
        if type(left) != type(right):
            log.info("Exit 1 - Different types")
            return False

        elif type(left) is dict:
            # Dict comparison
            for key in left:
                if key not in right:
                    log.info("Exit 2 - missing {} in right".format(key))
                    return False
                else:
                    if not deep_compare(left[str(key)], right[str(key)], level +1 ):
                        log.info("Exit 3 - different children")
                        return False
            return True
        elif type(left) is list:
            # List comparison
            for key in left:
                if key not in right:
                    log.info("Exit 4 - missing {} in right".format(key))
                    return False
                else:
                    if not deep_compare(left[left.index(key)], right[right.index(key)], level +1 ):
                        log.info("Exit 5 - different children")
                        return False
            return True
        else:
            # Other comparison
            return left == right

        return False

它比较dict,list和其他自己实现“ ==”运算符的类型。 如果您需要比较其他不同的东西,则需要在“如果树”中添加一个新分支。

希望有帮助。