One Type for pattern matching a sequence and dictionary
Greetings all, We can do one type annotations like list[int] and dict[str, int], my question: why don’t we have a similar thing in matching patterns? Especially if you want to enforce a type on a sequence or a dictionary with unknown length. For example, ls = [3.14, ‘hello’, 1, 2, 3, 4, ...] d = {‘name’: 1, ‘age’: 25, ...} match ls: case [float(), str(), *rest] if all(isinstance(elem, int) for elem in rest): ... (do something with rest) We do the same thing with the following: case [float(), str(), *int() as rest]: (do something with rest) match d: case **rest if all(isinstance(k, str) and isinstance(v, int) for k, v in rest.items()): (do something with rest) We do the same thing with the following: case **{str() as keys: int() as values} as rest: (do something with rest or with keys (=rest.keys()) and values (=rest.values()) directly) {str() as k: int() as v} matches a dictionary that has at least one structure of str(): int() but what would the values of k and v be in this case? Is It the first match since python dictionaries are now ordered? Or this is not permitted in dictionary matching? I saw examples like {‘string literal’: int() as v} on the web. What do you think of this idea? Abdulla
participants (1)
-
Abdulla Al Kathiri