[英]Comparing Python objects from deepcopy
有沒有辦法將 Python 對象與從深拷貝生成的對象進行比較?
例如:
import copy
original_object = SomeObject()
cloned_object = copy.deepcopy(original_object)
assertDeepCopy(original_object, cloned_object)
這就是我相信你的要求:
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
但請注意,這可能會在許多地方出錯:如果對象沒有以您喜歡的方式定義==
,您將無法獲得所需的答案。
我知道這是一個古老的答案,但是使用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和任何其他實現“==”運算符的類型。 如果您需要比較其他不同的東西,則需要在“if tree”中添加新分支。
希望有所幫助。
該解決方案允許您深入比較對象、字典、列表和原語。 它允許您從比較中排除鍵。
我認為這可能對某些尋求與對象支持進行深入比較的人有所幫助:)
def deep_compare(left, right, excluded_keys = []):
# convert left and right to dicts if possible, skip if they can't be converted
try:
left = left.__dict__
right = right.__dict__
except:
pass
# both sides must be of the same type
if type(left) != type(right):
return False
# compare the two objects or dicts key by key
if type(left) == dict:
for key in left:
# make sure that we did not exclude this key
if key not in excluded_keys:
# check if the key is present in the right dict, if not, we are not equals
if key not in right:
return False
else:
# compare the values if the key is present in both sides
if not deep_compare(left[key], right[key], excluded_keys):
return False
# check if any keys are present in right, but not in left
for key in right:
if key not in left and key not in excluded_keys:
return False
return True
# check for each item in lists
if type(left) == list:
# right and left must have the same length
if len(left) != len(right):
return False
# compare each item in the list
for index in range(len(left)):
if not deep_compare(left[index], right[index], excluded_keys):
return False
# do a standard comparison
return left == right
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.