https://github.com/python/cpython/commit/560738126e42208e71fa372c2826f9ccda3e4068
commit: 560738126e42208e71fa372c2826f9ccda3e4068
branch: main
author: Alex Malyshev <[email protected]>
committer: ambv <[email protected]>
date: 2026-10-08T14:32:33-07:00
summary:

gh-156491: Avoid KeyErrors in os._Environ.get() and __contains__() (GH-156492)

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.

files:
M Lib/os.py

diff --git a/Lib/os.py b/Lib/os.py
index 87547e369db817c..98d476f98419b20 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.
+_MISSING = sentinel("MISSING")
+
+
 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), _MISSING)
+        return default if val is _MISSING else self.decodevalue(val)
+
     def setdefault(self, key, value):
         if key not in self:
             self[key] = value

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to