@contextmanager<EOL>def environment(**kwargs):
old_values = {}<EOL>nonexistent = set()<EOL>for key in kwargs:<EOL><INDENT>if key not in os.environ:<EOL><INDENT>nonexistent.add(key)<EOL><DEDENT>else:<EOL><INDENT>old_values[key] = os.environ[key]<EOL><DEDENT>os.environ[key] = kwargs[key]<EOL><DEDENT>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>for key in old_values:<EOL><INDENT>os.environ[key] = old_values[key]<EOL><DEDENT>for key in nonexistent:<EOL><INDENT>os.environ.pop(key)<EOL><DEDENT><DEDENT>
Context manager to tempolrarily change environment variables. On exit all
variables are set to their original value.