1
y=5
id(5)
id(y)

In cpython the two id commands will return the same memory adddress, where the integer 5 is stored, but where in memory is the information that y is equal to 5 stored?

why is it important to be able to know where 5 is stored in memory, but not important to know where in memory y is equal to 5 is stored?

Also, is it possible to store the number 5 in more than one place in memory when using python? why or why not?

user3124200
  • 343
  • 1
  • 5
  • 1
    Please read https://docs.python.org/3/reference/datamodel.html – Dima Tisnek Mar 06 '19 at 02:34
  • Possible duplicate of [What is the id( ) function used for?](https://stackoverflow.com/questions/15667189/what-is-the-id-function-used-for) – Allan Mar 06 '19 at 02:36
  • In Python (the language) it is of no importance where any object or reference is stored in memory. The address is just used to have a safe hash value. – Klaus D. Mar 06 '19 at 02:43

1 Answers1

4

id(y) and id(5) say where the 5 in question is stored, not where y itself (the name) is stored.

The location of y itself (the name holding the pointer to the object representing 5) is an implementation detail; in CPython, function local names are stored in an array created when the function is called and cleaned when the function finishes, while global names are stored in a per-module dict (visible as globals()). The __code__ attribute of functions contains information about the locals, but doesn't provide direct access to the array (because that would allow Python code to break interpreter invariants, or take dependencies on implementation details that could change even between micro releases).

Knowing where 5 is isn't really important. The id function isn't intended to provide actual locations, that's just a convenient way to assign unique IDs that CPython uses. In non-CPython interpreters like PyPy, it doesn't actually have to describe a memory address at all (they assign unique IDs in other ways, because garbage collection means memory addresses aren't stable over the lifetime of an object). The point of the id is about identity; are these two things the same object (also testable with the is operator), not just equal in value.

As to your question "is it possible to store the number 5 in more than one place in memory when using python?", the answer for CPython is "No", but the language spec makes no such guarantee. id(y) and id(5) are the same only because of an implementation detail, the small int cache. On CPython, ints from -5 to 256 (inclusive) are singletons; no matter how you get them (math, parsing strings, literals, etc.) there is only one of each. But for ints outside that range, they're created on demand, so the ids won't overlap in most cases:

>>> y = 500
>>> id(y)
2538476592176
>>> id(500)
2538471826288
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271