Signature
id(__obj: object) -> int
Usage
id() function returns an integer, that is an unique identifier for the object. The id will be unique, and stays the same for the object lifetime.
NOTES
In Python, everything is an object, and this ID is a unique identifier for that object.
x = 100
y = "Big Box Code"
z = 9.99
print("Id of x:", id(x))
print("Id of y:", id(y))
print("Id of z:", id(z))
big_box_tuple = (100, 999, "BigBoxCode")
big_box_list = [100, 999, "BigBoxCode"]
big_box_dict = {"id": 100, "score": 99.99, "name": "BigBoxCode"}
print("Id of big_box_tuple: ", id(big_box_tuple))
print("Id of big_box_list: ", id(big_box_list))
print("Id of big_box_dict: ", id(big_box_dict))
PythonOutput:
Id of x: 140438421278032
Id of y: 140438420134256
Id of z: 140438419819792
Id of big_box_tuple: 140438420772928
Id of big_box_list: 140438420085120
Id of big_box_dict: 140438420086720
PlaintextParameters
Param Name | Type | Description |
---|---|---|
__obj | object | Object of concern, which we want to get the ID of |
Return Value
Type | Description |
---|---|
int | Integer representation of the object identity |
Retrieve Data from ID
import ctypes
x = 100
id_of_x = id(x)
object_from_id = ctypes.cast(id_of_x, ctypes.py_object)
print("Object from id: ", object_from_id)
print("Value from object(of id): ", object_from_id.value)
PythonOutput:
Object from id: py_object(100)
Value from object(of id): 100
PlaintextCompare Object IDs
x = 100
y = 100
print("Compare the id(x) and id(y): ", id(x) == id(y))
PythonOutput:
Compare the id(x) and id(y): True
PlaintextExamples
Here are some examples of id() function usage. We have tried to cover as many use cases as possible-
Example #1:
x = 100
y = 100
print("Compare the id(x) and id(y): ", id(x) == id(y))
PythonOutput:
Compare the id(x) and id(y): True
PlaintextDefinition in Source Code
// python/bltinmodule.c
/* AC: gdb's integration with CPython relies on builtin_id having
* the *exact* parameter names of "self" and "v", so we ensure we
* preserve those name rather than using the AC defaults.
*/
/*[clinic input]
id as builtin_id
self: self(type="PyModuleDef *")
obj as v: object
/
Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object's memory address.)
[clinic start generated code]*/
static PyObject *
builtin_id(PyModuleDef *self, PyObject *v)
/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
{
PyObject *id = PyLong_FromVoidPtr(v);
if (id && PySys_Audit("builtins.id", "O", id) < 0) {
Py_DECREF(id);
return NULL;
}
return id;
}
C