MCPcopy Index your code
hub / github.com/RustPython/RustPython / EnvironmentVarGuard

Class EnvironmentVarGuard

Lib/test/support/os_helper.py:737–794  ·  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

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

Callers 12

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
python_tzpath_contextMethod · 0.90
force_colorFunction · 0.85

Calls

no outgoing calls

Tested by 11

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
python_tzpath_contextMethod · 0.72