From cd4cfa6ed2fd5f866c7be339f1d3cf56aa4d2bad Mon Sep 17 00:00:00 2001 From: "d.grigonis" Date: Sat, 11 May 2024 23:55:23 +0300 Subject: [PATCH] gh-118932: ChainMap.__contains__ performance improvement (gh-118946) --- Lib/collections/__init__.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index d06d84cbdfc..a17100e6c02 100644 --- a/Lib/collections/__init__.py +++ b/Lib/collections/__init__.py @@ -1016,7 +1016,7 @@ class ChainMap(_collections_abc.MutableMapping): return self.__missing__(key) # support subclasses that define __missing__ def get(self, key, default=None): - return self[key] if key in self else default + return self[key] if key in self else default # needs to make use of __contains__ def __len__(self): return len(set().union(*self.maps)) # reuses stored hash values if possible @@ -1028,7 +1028,10 @@ class ChainMap(_collections_abc.MutableMapping): return iter(d) def __contains__(self, key): - return any(key in m for m in self.maps) + for mapping in self.maps: + if key in mapping: + return True + return False def __bool__(self): return any(self.maps)