Verify identity comparison using 'is' and 'is not' operators
Preconditions (2)
✅ Expected Result: The test passes confirming that 'is' correctly identifies identical objects and 'is not' correctly identifies different objects
import pytest def test_identity_operators(): # Two variables referencing the same list object a = [1, 2, 3] b = a # A different list object with the same content c = [1, 2, 3] # Assert that a and b are the same object assert a is b, "a and b should be the same object" # Assert that a and c are not the same object assert a is not c, "a and c should not be the same object"
This test defines three variables: a and b point to the same list object, while c points to a different list with the same content.
Using is checks if two variables point to the exact same object in memory. The assertion assert a is b confirms this.
Using is not checks if two variables do not point to the same object. The assertion assert a is not c confirms that although a and c have the same content, they are different objects.
Comments explain each step clearly for beginners.
Now add data-driven testing with 3 different pairs of variables to check identity and non-identity
is operator check in Python when used in pytest assertions?is operator meaningis operator checks if two variables refer to the same object in memory, not just equal values.==== operator checks if values are equal, but is checks identity (same object).is checks identity [OK]is means same object, not just equal value [OK]is with ==is checks value equalityis for comparing numbers or strings incorrectlya and b are not the same object in pytest?is not, so assert a is not b.!= which checks value inequality, not identity.is not syntax correct [OK]is not to check different objects, not != [OK]!= instead of is notis! which is invalid!== in Pythonobj1 = None obj2 = None assert obj1 is obj2
None is a singleton object, so all variables assigned None point to the same object.assert obj1 is obj2 checks if both variables point to the same object, which they do.None is None always True [OK]list1 = [1, 2, 3] list2 = [1, 2, 3] assert list1 is list2
assert list1 is list2 fails because is checks identity, not equality.== for value equality, is for identity [OK]is to check value equalityconfig every time it is called. Which assertion is best?is to check identity.is for singleton identity [OK]is to confirm same singleton object returned [OK]== which checks value, not identityis not by mistakePass the test and this pattern moves unknown