Skip to content

Instantly share code, notes, and snippets.

@zhiweio
Last active January 15, 2020 07:41
Show Gist options
  • Save zhiweio/741a7fb727d4715e1e85485ee1c07aea to your computer and use it in GitHub Desktop.
Save zhiweio/741a7fb727d4715e1e85485ee1c07aea to your computer and use it in GitHub Desktop.
递归比较 Python 数据类型
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import
from datetime import datetime, date
import collections
def recursive_compare(obj1, obj2):
""" Compare python objects recursively, support type:
"int, float, long, basestring, set, datetime, date, dict, Sequence"
Example:
>>> recursive_compare([1, 2, 3], [1, 2, 3])
>>> True
>>> recursive_compare([1, 2, 3], [1, 2, 4])
>>> False
>>> recursive_compare({'a': 1}, {'a': 2})
>>> False
"""
def _diff(obj1, obj2):
# exclude type basestring for backward-compatible python2:
# <str, unicode>
if type(obj1) != type(obj2) and not isinstance(obj1, basestring):
return False
elif isinstance(obj1,
(int, float, long, basestring, set, datetime, date)):
if obj1 != obj2:
return False
elif isinstance(obj1, dict):
keys = obj1.viewkeys() & obj2.viewkeys()
if obj1 and len(keys) == 0 \
or keys.difference(set(obj1.keys())) \
or keys.difference(set(obj2.keys())):
return False
for k in keys:
if _diff(obj1[k], obj2[k]) is False:
return False
elif isinstance(obj1, collections.Sequence):
# require sorted sequence object
if len(obj1) != len(obj2):
return False
for i in range(len(obj1)):
if _diff(obj1[i], obj2[i]) is False:
return False
elif isinstance(obj1, type(None)):
return
else:
raise TypeError('do not support type {} to compare'.format(
type(obj1)))
return False if _diff(obj1, obj2) is False else True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment