#Python tip: Structural pattern matching works with abstract base classes such as: Contains, Hashable, Iterable, Iterator, Reversible, Generator, Sized, Callable, and Collection.
match obj:
case Hashable:
...
Matching a collection ABC is preferable to looking for the required methods directly.
The complication is that those methods may be present but could be set to None.
The ABCs listed above handle the None checks for you.
For more complex ABCs, such as Sequence and Mapping, the presence of the required methods is insufficient.
The object's class needs to either inherit from the ABC or be registered with the ABC.
Note that matches only detect a promise that an API has been implemented. It can't detect whether a call to the API will succeed.
The classic example is that issubclass(tuple, Hashable) returns true, but hashing a tuple will fail if its components are unhashable.
Correction:
match obj:
case Hashable():
...
• • •
Missing some Tweet in this thread? You can try to
force a refresh
#Python's structural pattern matching is new, so the best practices aren't yet known.
Just added to my personal list: Add a comment or assertion noting when case ordering is important.
Otherwise, a future maintainer will be bitten by the illusion of case independence.
1 of 4
match x:
case bool():
...
case int():
assert not isinstance(x, bool)
...
case Counter():
...
case dict():
assert not isinstance(x, Counter)
case _:
raise TypeError
2 of 4
match sales_report:
case {'dept': dept, 'holiday': event}:
# Holiday case must precede other cases
...
case {'dept': 'shoes'}:
...
case {'dept': 'hats'}:
...
With dataclasses, you get nice attribute access, error checking, a name for the aggregate data, and a more restrictive equality test. All good things.
Dicts are at the core of the language and are interoperable with many other tools: json, **kw, …
@yera_ee Dicts have a rich assortment of methods and operators.
People learn to use dicts on their first day.
Many existing tools accept or return dicts.
pprint() knows how to handle dicts.
Dicts are super fast.
JSON.
Dicts underlie many other tools.
@yera_ee Embrace dataclasses but don't develop an aversion to dicts.
Python is a very dict centric language.
Mentally rejecting dicts would be like developing an allergy to the language itself. It leads to fighting the language rather than working in harmony with it.