[Python-ideas] Pattern matching

Szymon Pyżalski szymon at pythonista.net
Wed Apr 8 19:47:30 CEST 2015


On 08.04.2015 00:59, Andrew Barnert wrote:
>> "Works the same as __eq__" either doesn't allow you to assign parts while decomposing, or turns out to have a lot of problems.
The "works the same as __eq__" referers to simple objects like numbers,
strings or booleans. You could for example expect a tuple containing an
element that is some metadata with information, how to handle the data.
You could then use patterns like (True, Number), (False, Number).
>> The mapping is an interesting end-run around the decomposition problem, but it seems like it throws away the type of the object. In other words, Point(x, y) and Vector(x, y) both pattern-match identically to either {'x': x, 'y': y}. In ML or Haskell, distinguishing between the two is one of the key uses of pattern matching.
The mapping is only a way to populate the local namespace. If the
pattern matches or not is a different notion.

>> And another key use is distinguishing Point(0, y), Point(x, 0) and Point(x, y), which it looks like you also can't do this way; the only way to get x bound in the case block (assuming Point, like most classes, isn't iterable and therefore can't be decomposed as a tuple) is to match a dict.
I believe that objects that we want to be matchable in this way should
be subclasses of a namedtuple.------
> 
> * Types should match their instances
> 
>> This is an interesting idea. This allows you to do something halfway between taking any value and checking a specific value--and something that would often be useful in Python--which my proposal didn't have.

There is a problem with this idea. The isinstance method can accept a
tuple. And the tuple means "OR" in this case. In pattern matching
however the tuple would match a tuple. This is an ugly inconsistency.

Greetings
zefciu


More information about the Python-ideas mailing list