Variables are just memory references#

In Python, variables are not containers holding data directly but act as references to memory locations where the actual data is stored. This means that:

  • Variables point to objects in memory.

  • The same variable can point to different objects over time due to Python’s dynamic nature.

  • When you assign one variable to another, you are copying the reference, not the actual object.

name = "John"

What happens internally?#

  1. Object Creation: Python creates an object “John” if it does not already exist in memory. For small strings python uses string interning to reuse same object.

  2. Variable Binding: The variable a is created and points to the memory address of the string “b”.

  1. Reference Count: The string object’s reference count increases because a now refers to it.

Note

getrefcount creates an extra reference count

import sys
sys.getrefcount(id(name))
1
  1. Symbol Table Update: The variable a is added to the current scope’s symbol table, linking it to the “b” object.

print(globals()['name'])
John



Python is a Dynamically Typed Language#

In Python, variables do not have fixed types. The type of the object a variable points to is determined at runtime, allowing flexibility in assigning different types of objects to the same variable.

Key Characteristics:#

  • No Type Declaration: You don’t need to specify the type of a variable when declaring it.

a = 10       # Integer
a = "Hello"  # Now a string
  • Runtime Type Checking: The type of an object is checked when operations are performed, not at compile time.

a = 5 + "5"  # Raises a TypeError
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[5], line 1
----> 1 a = 5 + "5"  # Raises a TypeError

TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • Dynamic Reassignment: Variables can change their type by simply assigning a new value.