Untitled Python objects have the same identifier

Create two lists:

x = range(3) y = range(3) print id(x), id(y) 

Of:

 4366592912 4366591040 

I created two independent lists, and the output shows two different memory addresses. This is not surprising. But now do the same without assignment:

 id(range(3)) 

Of:

 4366623376 

And the second time:

 id(range(3)) 

Of:

 4366623376 

I am not sure how to interpret this. Why do these two unnamed lists have the same memory address?

+6
source share
2 answers

From the id(object) document :

Return the "identifier" of the object. This is an integer that is guaranteed to be unique and constant for this object throughout its life. Two objects with non-overlapping lifetimes can have the same id () value.

Because the two ranges inside id() calls have non-overlapping lifetimes, their id values ​​may be the same.

The two ranges assigned to the variables have overlapping lifetimes, so they must have different id values.

Edit:

A look at the sources of C shows us builtin_id :

 builtin_id(PyObject *self, PyObject *v) { return PyLong_FromVoidPtr(v); } 

and PyLong_FromVoidPtr .

 PyLong_FromVoidPtr(void *p) { #if SIZEOF_VOID_P <= SIZEOF_LONG return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p); #else #ifndef HAVE_LONG_LONG # error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long" #endif #if SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p); #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */ } 

Thus, the identifier is a memory address.

+13
source

The first object fell out of scope by the time the second object was created.

I don't know if python is a little smarter under the hood and recognizes that the second object is exactly the same as the first object (which is now out of scope) and just reuses the same address for it?

0
source

Source: https://habr.com/ru/post/972378/


All Articles