Skip to main content

How to Resolve SyntaxError: name 'X' is used prior to global declaration in Python

The SyntaxError: name 'X' is used prior to global declaration occurs in Python when you attempt to use a variable within a function before you declare your intention to modify the global variable of that same name using the global keyword within that function.

This guide explains the cause of this syntax error and how to resolve it correctly.

Understanding the Error: Local vs. Global Scope

Python functions have their own local scope. When you use a variable name inside a function, Python first checks if that name exists locally.

  • If you only read a variable that isn't defined locally, Python looks for it in the global scope.
  • However, if you assign a value to a variable within a function (e.g., my_var = ...), Python, by default, treats it as a new local variable, even if a global variable with the same name exists.

The SyntaxError happens because Python sees you using the variable (e.g., in print(employees)) before the global employees statement tells the function, "Hey, when I mention 'employees' later in this block, I mean the global one, not a new local one." Python requires this declaration to happen before any use of the variable within that same scope if you intend to modify the global one later in that scope.

Error Example:

employees = ['Alice', 'Bob'] # Global variable

def my_func():
# Using 'employees' BEFORE the global declaration
# print(employees) # ⛔️ SyntaxError: name 'employees' is used prior to global declaration

global employees # Declaring intent to modify the global 'employees'

# This assignment now refers to the global 'employees'
employees = ['Carl', 'Dean']

# my_func() # This call would trigger the SyntaxError at compile time

The global Keyword: Purpose and Placement

The global keyword tells Python that within the current function scope, any assignments or deletions involving the specified variable name should refer to the variable in the global (module-level) scope, not create a new local variable.

Crucially, the global statement must appear before any use (read or write) of that variable within the function's scope.

Solution: Move global Declaration to the Top

The fix is simple: move the global statement to the beginning of the function, before the variable is referenced in any way.

employees = ['Alice', 'Bob'] # Global variable

def my_func():
global employees # ✅ Moved to the top

# Now it's okay to access the global variable
print(f"Before reassignment: {employees}")

# This assignment modifies the GLOBAL variable
employees = ['Carl', 'Dean']
print(f"After reassignment: {employees}")

my_func()
print(f"Global employees after first call: {employees}") # Shows ['Carl', 'Dean']

# Calling again shows the updated global value
my_func()
print(f"Global employees after second call: {employees}") # Still ['Carl', 'Dean']

Output:

Before reassignment: ['Alice', 'Bob']
After reassignment: ['Carl', 'Dean']
Global employees after first call: ['Carl', 'Dean']
Before reassignment: ['Carl', 'Dean']
After reassignment: ['Carl', 'Dean']
Global employees after second call: ['Carl', 'Dean']

When global is Not Needed (Reading and Modifying Mutable Objects)

You do not need the global keyword if you are only reading the global variable or modifying a mutable global object (like a list or dictionary) in-place without reassigning the variable itself.

employees = ['Alice', 'Bob'] # Global list (mutable)

def read_global():
# No 'global' needed just to read
print(f"Reading global: {employees}")

def modify_global_list():
# No 'global' needed to modify the list's contents in-place
employees.append('Carl')
print(f"Modified global list: {employees}")

read_global() # Output: Reading global: ['Alice', 'Bob']
modify_global_list() # Output: Modified global list: ['Alice', 'Bob', 'Carl']
print(f"Global list now: {employees}") # Output: Global list now: ['Alice', 'Bob', 'Carl']
warning

While modifying global mutable objects from within functions works without the global keyword, it can make code harder to understand and debug. It's often better practice to pass such objects as arguments and return the modified version, or encapsulate state within classes.

When global Is Needed (Reassignment and Deletion)

You must use the global keyword if you intend to:

  • Reassign the global variable to a completely new object within the function.
  • Delete the global variable using del from within the function.
count = 0                               # Global integer (immutable)

def increment_global_count():
global count # NEEDED to reassign the global 'count'
count += 1
print(f"Count incremented to: {count}")

def delete_global_count():
global count # NEEDED to delete the global 'count'
print(f"Deleting global count (was {count})")
del count

increment_global_count() # Output: Count incremented to: 1
print(f"Global count is now: {count}") # Output: Global count is now: 1
delete_global_count() # Output: Deleting global count (was 1)

try:
print(count)
except NameError as e:
print(e) # Output: name 'count' is not defined

Conclusion

The SyntaxError: name 'X' is used prior to global declaration arises from referencing a variable before declaring it global within the same function scope when you intend to modify or delete the global variable later in that scope.

  • The solution is to place the global variable_name statement at the very beginning of the function, before any use of the variable.
  • Remember that global is only required for reassignment or deletion, not for reading global variables or modifying mutable global objects in-place (though the latter should be done with care).