On 12/17/2010 6:21 PM, Eike Welk wrote:
After learning a bit of Ocaml I started to like its pattern matching features.
Since then I want to have a "match" statement in Python. I wonder if anybody
else would like this too.
1. completely redundant with respect to current Python syntax;
2. look like chicken scratches;
3. limited by the chars availables to just a few of the infinity of tests one might want to run.
4. gives special prominence to tuples, which is hardly appropriate to list or iterable-oriented code.
I'm skeptical that anything is worth adding here, but here's an alternative. I'm only looking at the decomposition part. I'm using a matches keyword and "&" and "*". (The choice here doesn't matter but I have to use something for the examples, so please don't pick on that aspect.)
x = (3, 4)
if isinstance(x, tuple) and len(x) == 2:
a, b = x
print(a, b)
Or a bit more complicated:
x = [3, 4]
if isinstance(x, list) and x[0] == 3:
_, b, *_ = x
print(b)
and
if isinstance(x, dict) and j in x and len(x) == 1:
Here's a more complex example:
x matches {
'account': (&username, &domain),
'type': 'administrator',
'password': &hash,
'friends': (&best_friend, *&other_friends),
*
}
Whether or not this is useful at all is a big question, but I think it's at least more interesting. This isn't perfect. For example
x matches Foo(a=&alpha, b=&beta)
could mean checking x.hasattr('a') but there's no guarantee that Foo(a=1, b=2) will produce that result. Maybe that's OK.
Also, any values on the right hand side not marked by & are matched for equality, so you could write
x matches (3 * 14 + big_complicated_expression, &y)
which is pretty ugly. And that suggests:
which either doesn't make sense or is messy. We could add a __matches__ attribute to functions so they could support this, but now this is getting pretty complicated for unclear benefit.
--- Bruce