Last updated: Jul 10, 2022
Photo from Unsplash
To delete a global variable from inside a function:
globalkeyword to mark the variable as global inside of the function.
delstatement to delete the variable.
my_var = 'hello world' def my_func(): global my_var del my_var print(my_var) # 👉️ 'hello world' my_func() # ✅ Variable is now deleted # ⛔️ NameError: name 'my_var' is not defined print(my_var)
You can reference the global
my_var variable from inside the function, but if
you try to delete it in the function's body, you'd get an error.
The same is the behavior if you want to reassign a global variable from inside a function.
name = 'Alice' def example(): # 👇️ mark global global name print(name) # 👇️ reassign global variable from inside function name = 'Bob' example() # 👉️ 'Alice' example() # 👉️ 'Bob'
If a variable is assigned a value in a function's body, it is a local variable
unless explicitly declared as
You could reference the global
name variable from inside the function, but if
you assign a value to the variable in the function's body, the local variable
shadows the global one (unless you mark the variable as