id()
The built-in id()
function returns the identity of an object, which is a unique and constant integer that identifies the object during its lifetime.
In CPython, this identity corresponds to the memory address where the object resides:
>>> id(42)
4315605776
>>> id("Python")
4315120464
id()
Signature
id(object)
Arguments
Argument | Description |
---|---|
object |
The object to query |
Return Value
- Returns an integer representing the identity of the input object.
id()
Examples
With an integer as an argument:
>>> id(42)
4343440904
With a float as an argument:
>>> id(3.14)
4376764112
With a list as an argument:
>>> id([1, 2, 3])
4399577728
id()
Common Use Cases
The most common use cases for the id()
function include:
- Debugging to check if two variables point to the same object
- Understanding object lifecycle and memory management
- Inspecting how Python handles object references
id()
Real-World Example
Say you want to implement a Fibonacci-like sequence with a caching mechanism to store computed values. You can use the id()
function to verify that cached values are reused:
fibonacci.py
class Fibonacci:
def __init__(self, initial_value=1):
self._cache = [0, initial_value]
def __call__(self, index):
if index < len(self._cache):
fib_number = self._cache[index]
print(f"{index} {fib_number} id = {id(fib_number)}")
else:
fib_number = self(index - 1) + self(index - 2)
self._cache.append(fib_number)
return fib_number
fibonacci_333 = Fibonacci(333)
fibonacci_333(2)
fibonacci_333(4)
This example prints the identity of each number in the sequence, allowing you to verify that the same objects are used when expected, confirming the cache’s effectiveness.
Related Resources
Tutorial
Memory Management in Python
Get ready for a deep dive into the internals of Python to understand how it handles memory management. By the end of this article, you’ll know more about low-level computing, understand how Python abstracts lower-level operations, and find out about Python’s internal memory management algorithms.
For additional information on related topics, take a look at the following resources:
- Your Guide to the CPython Source Code (Tutorial)
- How Python Manages Memory (Course)