Open DamianBarabonkovQC opened 1 year ago
Have you considered Or(Match(structure), default)
?
Match
is specifically designed for checking structure in a flexible and concise way.
edit: docs https://glom.readthedocs.io/en/latest/matching.html
For the exact example you gave:
good_data = {"a": {"c": 1}}
bad_data = {"a": [{"c": 1}]}
The reason PathAccessError
gave ValueError
is that "a" and "b" are being interpreted as Paths -- you could do "a.b"
instead of ("a", "b")
and get the exact same result. As a Path, "a.0.c"
will unpack the bad-data. When it sees a list in the target, it tries to parse the corresponding Path segment as an int to use as the list index.
This can be made less ambiguous by using glom.T
. T["a"]["b"]
will try to do __getitem__()
in both cases.
Although, still I think that Match
is really the bigger brother of Coalesce
and probably what you want.
Feature Description
I have found a use-case of glom while programming my project where I believe more granular exception filtering in
Coalesce
may be beneficial. Namely, I may wish thatCoalesce
filter out an exception related to parsing ajson
of expected structure, but still raise when the structure deviates from the expected. I am fully willing to undertake the development of this feature. I am making this issue to start a discussion on such an addition.Example
To explain this better, here is the following example:
The motivation is to benefit from the
default
result fromCoalesce
if ajson
fails to parse, yet not silently allowing possibly buggy code to run where the expected structure of thejson
is completely different from that what is programmed in the glom specification.For example, the expected form of the json is a dict within a dict. Much like:
In this example, running a regular dict look-up produces a
PathAccessError
as such:If fed data in a different form, such as:
The glom look-up still produces a
PathAccessError
, but with a differing exception inside:Currently,
Coalesce
exception filtering is not granular enough to where I am able to filter out the correctly formed exception based on the internalKeyError
, while still raising the malformed one.The internal exception of a
PathAccessError
is accessible via aexc
attribute of the exception object.I am writing this issue to open a discussion on potentially introducing this ability, and how would be a good way to do this.