0
0
PyTesttesting~5 mins

Checking identity (is, is not) in PyTest

Choose your learning style9 modes available
Introduction

We use identity checks to see if two things are exactly the same object in memory, not just equal in value.

When you want to confirm two variables point to the exact same object.
When testing if a function returns a singleton like None or True.
When checking if two references are not the same object.
When you want to avoid confusing objects that look equal but are different.
When verifying caching or memoization returns the same object.
Syntax
PyTest
assert a is b
assert a is not b

is checks if two variables refer to the same object.

is not checks if two variables do not refer to the same object.

Examples
Both variables point to the same None object, so the test passes.
PyTest
a = None
b = None
assert a is b
Both variables refer to the same list object.
PyTest
a = [1, 2]
b = a
assert a is b
Lists have the same content but are different objects, so the test passes.
PyTest
a = [1, 2]
b = [1, 2]
assert a is not b
Sample Program

This test checks identity using is and is not. It shows when objects are the same or different.

PyTest
import pytest

def test_identity_checks():
    x = None
    y = None
    assert x is y  # Both None, same object

    a = [1, 2, 3]
    b = a
    assert a is b  # Same list object

    c = [1, 2, 3]
    assert a is not c  # Different list objects

    d = True
    e = True
    assert d is e  # True is a singleton

    f = 1000
    g = 1000
    assert f is not g  # Large integers may be different objects

if __name__ == '__main__':
    pytest.main([__file__])
OutputSuccess
Important Notes

Use is only to check identity, not equality of values.

For value equality, use == instead.

Singletons like None, True, and False are good examples for identity checks.

Summary

is checks if two variables point to the same object.

is not checks if two variables point to different objects.

Use identity checks to confirm exact object sameness, not just equal values.