What if your test says two objects are equal but they are actually different in memory?
Why Checking identity (is, is not) in PyTest? - Purpose & Use Cases
Imagine you have a list of user objects and you want to check if two variables point to the exact same user in memory. Doing this by manually comparing every attribute can be confusing and slow.
Manually comparing objects attribute by attribute is slow and error-prone. You might miss subtle differences or mistakenly think two objects are the same when they just look alike. This wastes time and causes bugs.
Using identity checks like is and is not in tests lets you quickly and clearly verify if two variables refer to the exact same object. This is faster, simpler, and less error-prone.
assert user1.id == user2.id and user1.name == user2.nameassert user1 is user2
This lets you confidently test if two variables point to the same object, catching subtle bugs and improving test clarity.
When testing a cache system, you want to confirm that fetching the same user twice returns the exact same object, not just a copy. Identity checks make this easy.
Manual attribute checks are slow and risky.
is and is not check if two variables point to the same object.
Using identity checks makes tests clearer and more reliable.