MCPcopy Index your code
hub / github.com/python/cpython / EnvironmentVarGuard

Class EnvironmentVarGuard

Lib/test/support/os_helper.py:738–795  ·  view source on GitHub ↗

Class to help protect the environment variable properly. Can be used as a context manager.

Source from the content-addressed store, hash-verified

736
737
738class EnvironmentVarGuard(collections.abc.MutableMapping):
739 """Class to help protect the environment variable properly.
740
741 Can be used as a context manager.
742 """
743
744 def __init__(self):
745 self._environ = os.environ
746 self._changed = {}
747
748 def __getitem__(self, envvar):
749 return self._environ[envvar]
750
751 def __setitem__(self, envvar, value):
752 # Remember the initial value on the first access
753 if envvar not in self._changed:
754 self._changed[envvar] = self._environ.get(envvar)
755 self._environ[envvar] = value
756
757 def __delitem__(self, envvar):
758 # Remember the initial value on the first access
759 if envvar not in self._changed:
760 self._changed[envvar] = self._environ.get(envvar)
761 if envvar in self._environ:
762 del self._environ[envvar]
763
764 def keys(self):
765 return self._environ.keys()
766
767 def __iter__(self):
768 return iter(self._environ)
769
770 def __len__(self):
771 return len(self._environ)
772
773 def set(self, envvar, value):
774 self[envvar] = value
775
776 def unset(self, envvar, /, *envvars):
777 """Unset one or more environment variables."""
778 for ev in (envvar, *envvars):
779 del self[ev]
780
781 def copy(self):
782 # We do what os.environ.copy() does.
783 return dict(self)
784
785 def __enter__(self):
786 return self
787
788 def __exit__(self, *ignore_exc):
789 for (k, v) in self._changed.items():
790 if v is None:
791 if k in self._environ:
792 del self._environ[k]
793 else:
794 self._environ[k] = v
795 os.environ = self._environ

Callers 14

setUpMethod · 0.90
do_test_with_pipMethod · 0.90
_check_sysMethod · 0.90
clear_envFunction · 0.90
setUpMethod · 0.90
test_getuserbaseMethod · 0.90
invoke_command_lineMethod · 0.90

Calls

no outgoing calls

Tested by 13

setUpMethod · 0.72
do_test_with_pipMethod · 0.72
_check_sysMethod · 0.72
clear_envFunction · 0.72
setUpMethod · 0.72
test_getuserbaseMethod · 0.72
invoke_command_lineMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…