Objects and ids
Every object has an identity that does not change during its lifetime. id(obj) returns that identity as an integer. is tests whether two names refer to the same object.
Detailed Explanation
Python distinguishes identity from equality. a is b asks "same object?". a == b asks "same value?". Two distinct lists can be equal. Two names can refer to one list. Assignment never copies: b = a makes b an alias, so b is a is true and mutating b mutates a.
id(obj) in CPython is the address of the object on the heap. That is an implementation detail. The language only promises a unique integer while the object is alive. After the object dies, CPython may reuse the address. Storing ids in a set as a long-term identifier is wrong; you can later see a new object with the same id. Compare live objects with is, or give them a real primary key.
Interning makes identity look like equality for some values. Small integers and some strings are reused, so 256 is 256 can be true and 257 is 257 can be false in the REPL. Never use is for numbers or strings. Use is for None, True, False, and sentinels you created with object().
True and False are singletons. None is a singleton. x is None is the correct test because x == None can be overridden by a broken __eq__. Custom sentinels should use the same pattern: MISSING = object() and x is MISSING.
Containers hold references. id(items[0]) is the id of the first element, not of a copy. Changing an element in place does not change the list's id. Rebinding items[0] = other changes which id sits in that slot.
__hash__ is allowed to use identity (hash(obj) defaults to id for user classes that have not defined __eq__). Once you define __eq__, you must define __hash__ or set it to None.
Code Examples
left = [1, 2]
right = left
copy = [1, 2]
print(left is right) # True
print(left is copy) # False
print(left == copy) # True
print(id(left) == id(right)) # TrueMISSING = object()
def read(row: dict, key: str):
return row.get(key, MISSING)
print(read({}, "qty") is MISSING) # True
print(read({"qty": 0}) is MISSING) # False# Do not persist ids. This can become true after `gone` is collected.
gone = []
old = id(gone)
del gone
print(id([]) == old) # sometimes True in CPythonCommon Gotchas
`is` for strings or ints
interning makes tests flake. Use `==`.
Storing `id(obj)` after `obj` is gone
the integer can be reused. Not a UUID.
`== None` can lie
a class that implements `__eq__` to always return `True` will match. Use `is None`.
`id` is not `hash`
equal objects can share a hash and still have different ids.