🐍 Python’s Scoping Surprise: The Need for the global Keyword

Python is a dynamically typed language that handles variable creation differently than statically typed languages like C++, C#, or Java. In Python, the act of assigning a value (=) defines the variable by binding a name to an object.

This model works seamlessly until you attempt to re-assign a global variable inside a function.

Imaging we have code below:

Scenario 1: Reading the Global Scope

When a function needs to read a global variable, Python has no problem finding it in the outer scope:

global_count = 100

def access_global():
   print(global_count)

access_global()
# outputs 100

Pretty straightforward, right?

Scenario 2: The Assignment Collision

The confusion arises when we try to change that variable within the function:

global_message = "Initial Global"
def modify_local():
    global_message = "Modified Locally"
    print(f"Inside function: {global_message}")
modify_local()
print(f"Outside function: {global_message}")
# Output:
# Inside function: Modified Locally
# Outside function: Initial Global

Wait, what? This is often the first major surprise for developers accustomed to automatic scope resolution.

This confusing behavior stems from Python’s LEGB (Local, Enclosing, Global, Built-in) rule: If a variable is assigned within a function, Python automatically treats it as a new local variable (shadowing the global one) unless told otherwise. If it is only read, Python searches up the scope chain and finds the global variable.

The Fix: Explicitly using global

So, how do we correctly modify the global variable? By using the mandatory global keyword.


global_message = "Initial Global"
def modify_global(): 
   global global_message
   global_message = "Modified Globally"
   print(f"Inside function: {global_message}")
modify_global()
print(f"Outside function: {global_message}")

# Output:
# Inside function: Modified Globally
# Outside function: Modified Globally

Key Takeaway

If you are just reading a global variable, no keyword is needed. If you intend to re-assign or mutate a global variable (change a list or dictionary in place), you must use the global keyword. If you forget this rule, your function will create a temporary local variable, and your global state modification will fail silently.