Test Overview
This test checks if two variables point to the exact same object in memory using is and is not operators. It verifies identity, not just equality.
This test checks if two variables point to the exact same object in memory using is and is not operators. It verifies identity, not just equality.
import pytest def test_identity(): a = [1, 2, 3] b = a c = [1, 2, 3] # Check that a and b are the same object assert a is b # Check that a and c are not the same object assert a is not c # Check that a and c have equal content assert a == c
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | Assign list [1, 2, 3] to variable a | Variable a points to a list object in memory | — | PASS |
| 3 | Assign variable b to reference the same object as a | Variables a and b point to the same list object | — | PASS |
| 4 | Assign variable c to a new list [1, 2, 3] | Variable c points to a different list object with same content | — | PASS |
| 5 | Assert that a is b (identity check) | a and b reference the same object | assert a is b | PASS |
| 6 | Assert that a is not c (identity check) | a and c reference different objects | assert a is not c | PASS |
| 7 | Assert that a == c (equality check) | a and c have equal content | assert a == c | PASS |
| 8 | Test ends | All assertions passed | — | PASS |
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