To unset environment variables in Python, the easiest way is to remove the variable from the os module environ dictionary with pop().
import os
os.environ.pop("VARIABLE_TO_UNSET", None)
You can also use del if you know the variable is in the environ dictionary. If the variable is not in the dictionary, you will get a KeyError.
import os
if "VARIABLE_TO_UNSET" in os.environ:
del os.environ["VARIABLE_TO_UNSET"]
When working with operating systems, the ability to set and unset environment variables easily can be valuable.
You can easily unset environment variables in Python.
With the os module environ dictionary, you can access the environment variables of the operating system.
To unset environment variables in Python, the easiest way is to remove the variable from the os module environ dictionary with pop().
You just need to pass the name of the environment variable to pop().
Below is a simple example showing you how to unset an environment variable in Python.
import os
os.environ.pop("VARIABLE_TO_UNSET", None)
Using del to Unset Environment Variable in Python
You can also use del if you know the variable is in the environ dictionary. del deletes the item from the dictionary of environment variables.
You do have to be careful here because if the variable is not in the dictionary, you will get a KeyError.
Below is an example of how you can unset an environment variable in Python with del.
import os
if "VARIABLE_TO_UNSET" in os.environ:
del os.environ["VARIABLE_TO_UNSET"]
Hopefully this article has been useful for you to learn how to unset environment variables in Python.