Sunday, 2 October 2022

How can I match against dictionaries containing arbitrary data types using the structural pattern matching feature in Python?

If I want to match against a list containing 2 elements (1 str, 1 bool) I can do the following:

match some_lst:
    case [str(), bool()]:  # -> Valid
        do_something()

How can I apply the same logic to dictionaries without using guards? For example, this doesn't work:

match some_dict:
    case {str(): bool()}:  # -> This is invalid
        do_something()

Working example with guard:

match some_dict:
    case dict() if all(isinstance(k, str) and isinstance(v, bool) for k, v in some_dict.items()):
        do_something()  # -> This works


from How can I match against dictionaries containing arbitrary data types using the structural pattern matching feature in Python?

No comments:

Post a Comment