dict.get_deep()

Chris Angelico rosuav at gmail.com
Sun Apr 3 11:07:18 EDT 2022


On Mon, 4 Apr 2022 at 00:59, Kirill Ratkin via Python-list
<python-list at python.org> wrote:
>
> 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.
>

You can use type names to require that it be that type:

case {"users": [{"address": {"street": str(street)}}]}:

ChrisA


More information about the Python-list mailing list