Object References

References in Python

  • In Python, all values are represented as objects.
  • An object is represented by a reference that points to the memory location of the object.

Thus, when a new object in Python is created, two entities are stored—the object, and a variable holding a reference to the object. All access to the object is through the reference value. A reference is a value that references, or “points to,” the location of another entity.

The value that a reference points to is called the dereferenced value.

We can get the reference value of a variable (that is, the location in which the corresponding object is stored) by use of built-in function id.

  • Python uses the same memory location for identical immutable objects to save memory. The n and k both reference the same instance of the integer 10, so id(n) and id(k) return the same address.
  • s references a different instance with the value 20, so id(s) returns a different address.

The Assignment of References

When variable n is assigned to k, it is the reference value of k that is assigned, not the dereferenced value 20

Thus, to verify that two variables refer to the same object instance, we can either compare the two id values by use of the comparison operator, or make use of the provided is operator (which performs id(k) == id(n)).

Both n and k reference the same instance of the literal value 20.

If the value of one of the two variables n or k is changed, they will point to different values and will no longer be equal.

  • Variable k is assigned a reference value to a new memory location holding the value 30.
  • Variable n still references the previous memory location, so n and k point to different values.

Memory Deallocation and Garbage Collection

When variables n and k are reassigned, the memory location storing the previous integer values can be deallocated.

Deallocation Process:

  • After n is reassigned to 40, the memory location storing the integer value 20 is no longer referenced.
  • Deallocation of a memory location means changing its status from "currently in use" to "available for reuse".
  • In Python, memory deallocation is automatically performed by a process called garbage collection.

Garbage Collection:

  • Garbage collection is a method of automatically determining which locations in memory are no longer in use and deallocating them.
  • The garbage collection process is ongoing during the execution of a Python program.