Find differences between two Python objects

Question:

Is there a way in Python to find the differences between two objects of the same type, or between two objects of any type? By differences I mean the value of one of their properties is different, or one object has a property that the other doesn’t. So for example:

dog.kingdom = 'mammal'
dog.sound = 'bark'

cat.kingdom = 'mammal'
cat.sound = 'meow'
cat.attitude = 'bow to me'

In this example, I’d want to know that the sound property is different, and the attitude property is only in cat.

The use case for this is I’m trying to override some default behavior in a library, and I’m setting up an object different than the library is but I don’t know what.

Asked By: jpyams

||

Answers:

print(dog.__dict__.items() ^ cat.__dict__.items())

Result:

{('attitude', 'bow to me'), ('sound', 'meow'), ('sound', 'bark')}

For set-like objects, ^ is the symmetric difference.

Answered By: Alex Hall

You can take a look at DeepDiff.

Between two instances of the same class :

from deepdiff import DeepDiff
from pprint import pprint

class Animal:
    pass

dog = Animal()
cat = Animal()

dog.kingdom = 'mammal'
dog.sound = 'bark'

cat.kingdom = 'mammal'
cat.sound = 'meow'
cat.attitude = 'bow to me'

differences = DeepDiff(dog, cat)
pprint(differences)
>> {'attribute_added': [root.attitude],
>>  'values_changed': {'root.sound': {'new_value': 'meow', 'old_value': 'bark'}}}

Between two instances of different classes :

from deepdiff import DeepDiff
from pprint import pprint

class Dog:
    pass

class Cat:
    pass

dog = Dog()
cat = Cat()


dog.kingdom = 'mammal'
dog.sound = 'bark'

cat.kingdom = 'mammal'
cat.sound = 'meow'
cat.attitude = 'bow to me'

differences = DeepDiff(dog, cat, ignore_type_in_groups=(Dog, Cat))
pprint(differences)
>> {'attribute_added': [root.attitude],
>>  'values_changed': {'root.sound': {'new_value': 'meow', 'old_value': 'bark'}}}
Answered By: LuoLeKe
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.