Last updated: Apr 10, 2024
Reading timeยท2 min
The Python "SyntaxError: name 'X' is used prior to global declaration" occurs
when we reference a variable in a function prior to marking it as global
.
To solve the error, move the global
declaration at the beginning of your
function's definition.
Here is an example of how the error occurs.
employees = ['Alice', 'Bob'] def my_func(): # โ๏ธ SyntaxError: name 'employees' is used prior to global declaration print(employees) global employees employees = ['Carl', 'Dean'] my_func()
The error is caused when we reference the variable before marking it as
global
.
global
statement to the top of the function definitionTo solve the error, move the global your_variable
statement to the top of the
function's definition before any references to the variable.
employees = ['Alice', 'Bob'] def my_func(): # ๐๏ธ Is now moved to the top global employees print(employees) employees = ['Carl', 'Dean'] my_func() # ๐๏ธ ['Alice', 'Bob'] my_func() # ๐๏ธ ['Carl', 'Dean']
We moved the global
statement to the top of the function which resolved the
error.
global
in the same code block preceding the global
statement.Once the global
statement runs, we can access the variable within the
function, update the variable's value or even delete it.
global
to access a global variableIf you only have to read the global variable within your function, you don't
have to use the global
statement.
employees = ['Alice', 'Bob'] def my_func(): print(employees) my_func() # ๐๏ธ ['Alice', 'Bob']
You can even modify the global variable from within the function, even though this isn't considered a good practice.
employees = ['Alice', 'Bob'] def my_func(): employees.append('Carl') print(employees) my_func() # ๐๏ธ ['Alice', 'Bob', 'Carl'] my_func() # ๐๏ธ ['Alice', 'Bob', 'Carl', 'Carl'] my_func() # ๐๏ธ ['Alice', 'Bob', 'Carl', 'Carl', 'Carl']
We are able to use the list.append()
method to modify the global employees
variable.
global
to reassign a global variableHowever, if you need to reassign the global variable from within the function,
you have to mark the variable as global
.
employees = ['Alice', 'Bob'] def my_func(): global employees print(employees) employees = ['Carl', 'Dean'] my_func() # ๐๏ธ ['Alice', 'Bob'] my_func() # ๐๏ธ ['Carl', 'Dean']
We had to use the global
statement at the top of the function's definition in
order to reassign the global employees
variable within the function.
global
to delete a global variableYou also have to use the global
statement if you have to delete a global
variable from within a function.
employees = ['Alice', 'Bob'] def my_func(): global employees print(employees) del employees my_func() # ๐๏ธ ['Alice', 'Bob'] # โ๏ธ NameError: name 'employees' is not defined my_func()
Once we mark the employees
variable as global
, we are able to use the del
statement to delete the variable from within the function.
You can learn more about the related topics by checking out the following tutorials: