1

Python documentation says "For each such variable, a cell object is created to store the value; the local variables of each stack frame that references the value contains a reference to the cells from outer scopes which also use that variable. "

So it seems that the cell object store the value of variables(like stored the copy of the value I assume?).

but when I run this:

def func():
    l = [1,2,3]
    def g():
        print(l)
    return l,g
l,g = func()
l[0]=-1
g()

The output is:

[-1, 2, 3]

The change of l does affect the value stored within the cell object. Then it seems to me that what was stored in the cell is the reference. Can someone explain this, please?

Axe319
  • 4,255
  • 3
  • 15
  • 31
Rylan Liu
  • 45
  • 3

1 Answers1

1

In the reference manual the value of the object is the mutable object itself, it is uniquely identified by the cell. It is not an immutable or abstract value. This term is used as a contrast to the reference, which is what is copied when you perform assignment, pass an argument to a function, etc.

Elazar
  • 20,415
  • 4
  • 46
  • 67
  • i think of reference as a mapping from the name of a object to the object in memory, is that correct ? and is it ok to think that a cell contains the mapping from the cell object to the object it contains in memory ? – Rylan Liu Oct 14 '21 at 06:31
  • The cell contains "the object itself". It is an abstract concept, but it is essentially the memory that holds the dictionary. – Elazar Oct 14 '21 at 07:53
  • The mapping from names to the cells is the environment of the program, the state at some program point at runtime. References can be accessed using names, but they can also be accessed by any other expression; the reference is the value (in the original abstract sense you talked about) that the expression is evaluated to at runtime. – Elazar Oct 14 '21 at 07:57
  • Note:the reference _is_ the value, it is a pointer value, though not necessarily one that corresponds directly to a machine address - it can be implemented as an array index, or as a name, or any other "key" that can be used later to refer to the cell - the actual set of memory locations. – Elazar Oct 14 '21 at 07:58
  • In CPython, a reference is a memory address, and a cell is a memory region accessible through that address, directly or indirectly – Elazar Oct 14 '21 at 08:02