What is the correct way to unset a linux environment variable in python?

Just

del os.environ['MYVAR']

should work.


You can still delete items from the mapping, but it will not really delete the variable from the environment if unsetenv() is not available.

del os.environ['MYVAR']

For those who search for an elegant way to unset environment variable without errors if the variable does not exist:

os.environ.pop('MYVAR', None)

That works exactly as:

if 'MYVAR' in os.environ:
    del os.environ['MYVAR']

But if you need to deal with the exception, do what other users suggested: del os.environ['MYVAR'] or os.environ.pop('MYVAR').