Delete global variable from inside a function in Python

avatar

Borislav Hadzhiev

Last updated: Jul 10, 2022

banner

Photo from Unsplash

Delete global variable from inside a function in Python #

To delete a global variable from inside a function:

  1. Use the global keyword to mark the variable as global inside of the function.
  2. Use the del statement to delete the variable.
main.py
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.

We can only delete a variable from the same scope in which it was declared, unless the variable has been marked as global.

The same is the behavior if you want to reassign a global variable from inside a function.

main.py
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 global.

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 global).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.