Hi Marco.
Recently I met same issue. A service I intergated with was documented
badly and sent ... unpredictable jsons.
And pattern matching helped me in first solution. (later I switched to
Pydantic models)
For your example I'd make match rule for key path you need. For example:
data = {"users": [{"address": {"street": "Baker"}}]}
match data:
case {"users": [{"address": {"street": street}}]}:
print(f"street: {street}")
case _:
print("unsupported message structure")
Structural matching gives you warranty you process exactly message you
expect and explicitly discards messages with another structure.
But type is still issue. I don't know how to say 'street' must be 'str'
not 'int'. That's why I switched to Pydantic.
02.04.2022 23:44, Marco Sulla пишет:
A proposal. Very often dict are used as a deeply nested carrier of
data, usually decoded from JSON. Sometimes I needed to get some of
this data, something like this:
data["users"][0]["address"]["street"]
What about something like this instead?
data.get_deep("users", 0, "address", "street")
and also, instead of this
try:
result = data["users"][0]["address"]["street"]
except KeyError, IndexError:
result = "second star"
write this:
data.get_deep("users", 0, "address", "street", default="second star")
?
--
https://mail.python.org/mailman/listinfo/python-list