Skip to main content

Command Palette

Search for a command to run...

Understanding Dynamic Variable Allocation in Python

Updated
2 min read
Understanding Dynamic Variable Allocation in Python

I was always curious about how Python assigns values under the hood to the same variable.

Example

Let's say we declare:

a = 2
print(type(a))  # This will give INT as a response
a = 2
a = "Hello World"
print(type(a))  # This will give String as a response

This is where the interest pops up that a was initially an INT but suddenly converted to a String.

How it works

It uses objects when assigning values to variables and it does it at runtime.

  • When we say a = 2:

    • At runtime, it creates an object of INT and assigns the value of 2 to that object.

    • It increments the reference count by 1.

    • It assigns the reference of that object to the a variable.

  • When we reassign "Hello World" (a string value) to a:

    • In the background, it creates another object of String with the value "Hello World" assigned to it.

    • It increments the reference of the new object's count by 1.

    • The reference of this newly created object is assigned to the a variable.

    • The reference count for the INT object decreases by 1.

When the reference count of an object hits 0, it becomes eligible for garbage collection. At runtime, the Python garbage collector collects the INT object as it doesn't have any references and the reference count is set to 0.