From 39193becb38ceeeee0f0bea031284c9275205318 Mon Sep 17 00:00:00 2001 From: Alex Malyshev Date: Thu, 27 Aug 2026 14:56:47 -0400 Subject: [PATCH 1/2] Avoid KeyErrors in os._Environ.get() and __contains__() Implement get() and __contains__() on os._Environ directly, which cuts out the cost of raising and catching a KeyError when the keys do not exist. --- Lib/os.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Lib/os.py b/Lib/os.py index 87547e369db817c..f932e7af48028d4 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -720,6 +720,11 @@ def get_exec_path(env=None): # Change environ to automatically call putenv() and unsetenv() from _collections_abc import MutableMapping, Mapping +# Sentinel used for seeing if a value is found within the internal _Environ +# dictionary. +_environ_missing = object() + + class _Environ(MutableMapping): def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue): self.encodekey = encodekey @@ -728,6 +733,9 @@ def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue): self.decodevalue = decodevalue self._data = data + def __contains__(self, key): + return self.encodekey(key) in self._data + def __getitem__(self, key): try: value = self._data[self.encodekey(key)] @@ -770,6 +778,10 @@ def __repr__(self): def copy(self): return dict(self) + def get(self, key, default = None): + val = self._data.get(self.encodekey(key), _environ_missing) + return default if val is _environ_missing else self.decodevalue(val) + def setdefault(self, key, value): if key not in self: self[key] = value From d13030ba3acd620e12746083e72b07a5a39bf58f Mon Sep 17 00:00:00 2001 From: Alex Malyshev Date: Thu, 27 Aug 2026 16:39:24 -0400 Subject: [PATCH 2/2] Switch to using a sentinel() --- Lib/os.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Lib/os.py b/Lib/os.py index f932e7af48028d4..c969281abf95f60 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -722,7 +722,7 @@ def get_exec_path(env=None): # Sentinel used for seeing if a value is found within the internal _Environ # dictionary. -_environ_missing = object() +_MISSING = sentinel("MISSING") class _Environ(MutableMapping): @@ -779,8 +779,8 @@ def copy(self): return dict(self) def get(self, key, default = None): - val = self._data.get(self.encodekey(key), _environ_missing) - return default if val is _environ_missing else self.decodevalue(val) + val = self._data.get(self.encodekey(key), _MISSING) + return default if val is _MISSING else self.decodevalue(val) def setdefault(self, key, value): if key not in self: