Skip to content

nested.get_by_path fails with default #80

@boeddeker

Description

@boeddeker

@thequilo Do you remember, why the default is only considered for KeyError and IndexError?
When should get_by_path fail?

except Exception as e:
# Indexing a custom type can raise any exception, in which case
# we try to broadcast
# Not sure if broadcasting makes sense for lists/tuples. It is
# hard to check for custom sequences because of str, so
# sequences are broadcasted here
if allow_early_stopping and not isinstance(container, Mapping):
return container
# We can't add another more specific except block because we have to
# catch all exceptions for the broadcasting. Assuming here that
# custom containers raise KeyErrors and IndexErrors correctly when
# the indexed element is not found
if isinstance(e, (KeyError, IndexError)):
if default is not _NO_VALUE:
return default
raise

Here, an extension of the doctest. IMHO the last example should work.

>>> d = {'a': 'b', 'c': {'d': {'e': 'f'}, 'g': [1, [2, 3], 4]}}
...
>>> get_by_path(d, 'c.b.c', default=42)
42
>>> get_by_path(d, 'a.b.c', default=42)
Traceback (most recent call last):
...
TypeError: string indices must be integers

The leafs in a nested structure can have any type and hence any Exception could be thrown.
So I don't get, why there is an if statement.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions