Advertisement
Guest User

Untitled

a guest
Jan 25th, 2024
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. from typing import cast, Mapping, Any, TypeVar
  2.  
  3.  
  4. T = TypeVar("T")
  5.  
  6. _NOT_SPECIFIED = cast(T, object())  # type: ignore
  7.  
  8.  
  9. def dict_lookup(source: Mapping[Any, T], *keys: Any, default: T = _NOT_SPECIFIED) -> T:
  10.     """
  11.    Lookup *keys recursively in source.
  12.    Raises KeyError on the first missing key, unless a default is specified.
  13.  
  14.    e.g.:
  15.        example = {'nested': {'key': {'lookup': True}}}
  16.        assert dict_lookup(example, 'nested', 'key', 'lookup') == True
  17.    """
  18.     if not keys:
  19.         return cast(T, source)
  20.  
  21.     try:
  22.         return dict_lookup(source[keys[0]], *keys[1:])  # type: ignore
  23.  
  24.     except KeyError:
  25.         if default is _NOT_SPECIFIED:
  26.             raise
  27.         return default
  28.  
  29.     except (IndexError, TypeError):
  30.         # can happen when non-dict types are found
  31.         raise KeyError(keys)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement