In the below diagram, I have a query on name temp
that is returned from function f
In local frame f
, temp
is a reference variable pointing to an object 6
of class int
, when you say return temp
in f
a reference variable output
which is part of checkPassingMech
frame will point to the same object 6
that temp was pointing to.
My question:
Q1) Is my understanding correct?
Q2) If Q1 is yes, then this diagram is giving an illusion that temp
is not reference type and showing its value in a box rather than with an arrow pointing to 6, am i correct?
Q3) If Q2 is yes, then, Can i say that 6
is actually stored in heap and temp
and output
would be pointing to this heap space from frame(local stack)
>>> def f():
temp = 6
print(id(temp))
return temp
>>> output = f()
507107408
>>> id(output)
507107408
from doc:
CPython implementation detail: For CPython, id(x) is the memory address where x is stored.
So strictly speaking, if the value is 6, then output
and temp
is actually pointing to the same object, which is an int
object that is cached when python started.
You may refer to identifying objects, why does the returned value from id(...) change? for more information.
Yes, your understanding is correct, besides Python's runtime only deals in references to objects (which all live in the heap): what goes on Python's stack (as operands and results of its bytecode operations) are always references (to values that live elsewhere).
All Python objects in the CPython implementation go on the heap. You can read in detail how Python's memory management works here in the documentation:
Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching.
"Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)"
https://docs.python.org/2/reference/datamodel.html
So you wouldn't be able to just put an arrow pointing at 6, because it is not guaranteed to be the same reference to 6 each time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With