I would love to see this implemented! Off course I like my syntax better. :-) On Saturday 18.12.2010 22:26:05 Bruce Leban wrote:
x = (3, 4) if x matches (&a, &b): print(a, b)
is equivalent to
x = (3, 4) if isinstance(x, tuple) and len(x) == 2: a, b = x print(a, b)
...
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)
For this case I prose that the class "Foo" should implement a special function "__rinit__" that breaks an instance apart, into components that can be matched. These components should be chosen so that they could be given to "__init__" as its arguments. "__rinit__" should return the following objects: * a tuple of objects, corresponding to the regular arguments of "__init__". * a tuple of strings that contains the argument names. * a dict of string:object that represents the keyword only attributes. A simple class would look like this: class Foo(object): def __init__(self, c, d): self.c = c self.d = d def __rinit__(self): return (self.c, self.d), ("c", "d"), {} The example from above: x matches Foo(c=&gamma, d=&delta) would work like this: if isinstance(x, Foo): vals, names, kwargs = x.__rinit__() gamma = vals[names.index("c")] delta = vals[names.index("d")] Positional arguments are also possible: x matches Foo(&gamma, &delta) would work like this: if isinstance(x, Foo): vals, names, kwargs = x.__rinit__() gamma = vals[0] delta = vals[0] A type check would be expressed like this: x matches Foo(&*_)
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)
It's really neat, but maybe too much visual clutter. It should be discussed if the following looks better: x matches (x, y) and x == 3 * 14 + big_complicated_expression I'm unsure about it.
which is pretty ugly. And that suggests:
x matches (f(&y), g(&z))
It can only work with the few functions that are bijective. Many algorithms destroy information and can therefore not be run backwards.
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.
Eike