Skip to content

Commit

Permalink
Implement get on CaseInsensitiveDict
Browse files Browse the repository at this point in the history
get was previously provided by the parent class which
had to raise KeyError for missing values. Since try/except
is only cheap for the non-exception case the performance
was not good when the key was missing

similar to python/cpython#106665
but in the HA case we call this even more frequently
  • Loading branch information
bdraco committed Aug 13, 2023
1 parent ac4171a commit 8eb2c0f
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions async_upnp_client/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ def replace(self, new_data: abcMapping) -> None:
self._data = {**new_data}
self._case_map = {k.lower(): k for k in self._data}

def get(self, key: str, default: Any = None) -> Any:
"""Get item with default.
This implementation is case insensitive and avoids
calling __getitem__ which would raise KeyError and
cause unnecessary exception handling.
"""
data_key = self._case_map.get(key.lower(), _SENTINEL)
if data_key is not _SENTINEL:
return self._data.get(data_key, default)
return default

def __setitem__(self, key: str, value: Any) -> None:
"""Set item."""
lower_key = key.lower()
Expand Down

0 comments on commit 8eb2c0f

Please sign in to comment.