4 ms·
IOW, the match/case tool can pattern match and destructure at the same time. Som uninterestingly, it is possible to do only one of those things: Iterator unpa
by raymondh 4y ago
IOW, the match/case tool can pattern match and destructure at the same time. Som uninterestingly, it is possible to do only one of those things:
Iterator unpacking:
first, *middle, last = t
is similar to a match/case with a sequence pattern:
match t:
case first, *middle, last:
...
The former works for any iterable and the latter requires a sequence. The former raises an error for a non-iterable and the latter just skips the case for a non-sequence. Otherwise, they are similar.
However, arguing that one is a special case of the other misses the entire point of structural pattern matching. We would almost never substitute the latter for the former. They mostly live in different worlds because we use them and think about them much differently:
# Something that would work but they we don't do
for item in somedict.items():
match item:
case [key, value]:
print(key.upper())
print(value)
print()
case _:
raise RuntimeError('unexpected kind of item')
# What we actually do
for key, value in somedict.items():
print(key.upper())
print(value)
print()
Sorry for the small rant, but I think this pedantic point isn't a useful line of thinking. That concepts and implementation have some overlap but should occupy a different concept maps in our brains — very much like the idea that dicts can do set-like things but that we're better off thinking about dicts as doing lookups and sets as doing uniquification, membership-testing, and set-to-set operations.