jpyams
jpyams

Reputation: 4364

Find differences between two Python objects

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.

Upvotes: 21

Views: 20355

Answers (2)

LuoLeKe
LuoLeKe

Reputation: 155

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'}}}

Upvotes: 4

Alex Hall
Alex Hall

Reputation: 36033

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

Result:

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

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

Upvotes: 37

Related Questions