

def get_value_by_keypath(obj, keypath, **kwargs):
    "\n\n    >>> get_value_by_keypath([1, 2, 3], '[0]')\n    1\n    >>> get_value_by_keypath({'answer': 42}, 'answer')\n    42\n    >>> try:\n    ...     get_value_by_keypath({'answer': 42}, 'answer.k')\n    ... except KeyError as e:\n    ...     print(e)\n    'answer.k'\n    >>> get_value_by_keypath({'answer': 42}, 'answer.k', default='gg')\n    'gg'\n    >>> get_value_by_keypath({'answer': {'value': 42}}, 'answer.value')\n    42\n    >>> get_value_by_keypath({'answer': {'value': [41, 42, 43]}}, 'answer.value.[1]')\n    42\n    >>> try:\n    ...     get_value_by_keypath({'answer': {'value': [41, 42, 43]}}, 'answer.value.[3]')\n    ... except IndexError as e:\n    ...     print(e)\n    list index out of range\n    >>> get_value_by_keypath({'answer': {'value': [41, 42, 43]}}, 'answer.value.[3]', default='XD')\n    'XD'\n\n    :type obj: list[T]|dict[U,T]\n    :type keypath: str\n    :rtype: T\n    "
    if (len(keypath) == 0):
        raise KeyError(keypath)
    has_default = ('default' in kwargs)
    default = kwargs.get('default')
    target = obj
    for keypath_component in map(_keypath_component_handler, keypath.split('.')):
        if (isinstance(target, Sequence) and isinstance(keypath_component, int)):
            if ((keypath_component < len(target)) or (not has_default)):
                target = target[keypath_component]
            else:
                return default
        elif isinstance(target, dict):
            if has_default:
                target = target.get(keypath_component, default)
            else:
                target = target[keypath_component]
        elif has_default:
            return default
        else:
            raise KeyError(keypath)
    return target

dataset/ETHPy150Open sodastsai/taskr/taskr/contrib/collections.py get_value_by_keypath/original