Skip to content

Commit 39193be

Browse files
committed
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.
1 parent 45e5b1b commit 39193be

1 file changed

Lines changed: 12 additions & 0 deletions

File tree

Lib/os.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -720,6 +720,11 @@ def get_exec_path(env=None):
720720
# Change environ to automatically call putenv() and unsetenv()
721721
from _collections_abc import MutableMapping, Mapping
722722

723+
# Sentinel used for seeing if a value is found within the internal _Environ
724+
# dictionary.
725+
_environ_missing = object()
726+
727+
723728
class _Environ(MutableMapping):
724729
def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue):
725730
self.encodekey = encodekey
@@ -728,6 +733,9 @@ def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue):
728733
self.decodevalue = decodevalue
729734
self._data = data
730735

736+
def __contains__(self, key):
737+
return self.encodekey(key) in self._data
738+
731739
def __getitem__(self, key):
732740
try:
733741
value = self._data[self.encodekey(key)]
@@ -770,6 +778,10 @@ def __repr__(self):
770778
def copy(self):
771779
return dict(self)
772780

781+
def get(self, key, default = None):
782+
val = self._data.get(self.encodekey(key), _environ_missing)
783+
return default if val is _environ_missing else self.decodevalue(val)
784+
773785
def setdefault(self, key, value):
774786
if key not in self:
775787
self[key] = value

0 commit comments

Comments
 (0)