Python: the id() function and object equality: a word of caution

Python: the id() function and object equality: a word of caution

In Python the id() function should never be used to check the equality of two objects.

In Python the id() function should never be used to check the equality of two objects.

The id() function returns an integer representation of the object's identity, which is always different even if two or more instances of a class have exactly the same attributes and the same values for those attributes . At the CPython implementation level, it is the address of the object in memory.

Esempio:

class User:
    def __init__(self, name):
        self.name = name


user_1 = User('John')
user_2 = User('John')

print(id(user_1))
print(id(user_2))

We will get for example:

4479462576
4479462480

As you can see, the id() function returns two different values.