Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 247
jpyams Avatar asked Sep 05 '17 20:09

jpyams


People also ask

How do I find the difference between two objects in Python?

Comparing Equality With the Python == and !=Use the equality operators == and != if you want to check whether or not two objects have the same value, regardless of where they're stored in memory.

How do you check if two things are the same in Python?

Use the == operator to test if two variables are equal.


1 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.

like image 195
Alex Hall Avatar answered Sep 24 '22 17:09

Alex Hall