title: Temporarily modify the current process's environment
body: <p>I use the following code to temporarily modify environment variables. </p>
  
  <pre><code>@contextmanager
  def _setenv(**mapping):
      """``with`` context to temporarily modify the environment variables"""
      backup_values = {}
      backup_remove = set()
      for key, value in mapping.items():
          if key in os.environ:
              backup_values[key] = os.environ[key]
          else:
              backup_remove.add(key)
          os.environ[key] = value
  
      try:
          yield
      finally:
          # restore old environment
          for k, v in backup_values.items():
              os.environ[k] = v
          for k in backup_remove:
              del os.environ[k]
  </code></pre>
  
  <p>This <code>with</code> context is mainly used in test cases. For example,</p>
  
  <pre><code>def test_myapp_respects_this_envvar():
      with _setenv(MYAPP_PLUGINS_DIR='testsandbox/plugins'):
          myapp.plugins.register()
          [...]
  </code></pre>
  
  <p>My question: is there a simple/elegant way to write <code>_setenv</code>? I thought about actually doing <code>backup = os.environ.copy()</code> and then <code>os.environ = backup</code> .. but I am not sure if that would affect the program behavior (eg: if <code>os.environ</code> is <em>referenced</em> elsewhere in the Python interpreter).</p>