150

From the documentation:

If the platform supports the unsetenv() function, you can delete items in this mapping to unset environment variables. unsetenv() will be called automatically when an item is deleted from os.environ, and when one of the pop() or clear() methods is called.

However I want something that will work regardless of the availability of unsetenv(). How do I delete items from the mapping if it's not available? os.environ['MYVAR'] = None?

2
  • 1
    unsetenv works on "most flavors of Unix, Windows" according to the docs. Commented Aug 26, 2010 at 12:55
  • 1
    hmmm, I wasn't sure. I'm on a platform where $ unset MYVAR commands work Commented Aug 26, 2010 at 12:57

4 Answers 4

235

Just

del os.environ['MYVAR']

should work.

Sign up to request clarification or add additional context in comments.

6 Comments

The question was about removing items from the mapping, after all. If unsetenv is unsupported, then the key and value are removed from the mapping but remain set in the environment, neh?
If the key doesn't exist I think you get a KeyError.
for the record del os.environ worked for when os.unsetenv did not on OSX.
FYI this solution is not idempotent. i.e. if MYVAR doesn't exist in the environment, you will get an exception. You can wrap it in a try: but it's unfortunate.
|
63

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

Comments

12

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']

Comments

1

Try this if you need a valid method, such as in TestCase.addCleanup()

os.environ.pop('MYVAR')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.