gvanrossum / patma

Pattern Matching
1.02k stars 64 forks source link

Nick Coghlan's (revised) PEP 642 #166

Closed gvanrossum closed 3 years ago

gvanrossum commented 3 years ago

It seems in the latest revision of PEP 642 Nick is no longer proposing to use ? as a sigil, and he's proposing __ (double underscore!) as a wildcard.

I think the double underscore is a one of those Solomonic compromises intended to make everyone unhappy, but the other change (suggestedby Steven D'Aprano) seems worth at least thinking about.

PEP 642 is now proposing == and is to mark what type of comparison should be used, but allows to omit these in many cases that make it look similar to PEP 634.

In particular, case ==42: can be shortened to case 42, and case is None to case None.

Nick doesn't seem to like defaulting True and False to is -- I'm not sure why not, since they are singletons and keywords just like None, and he is also proposing case ... as a shortcut for case is ... (I'm not sure why he cares about ... in patterns at all -- maybe it's completionism.)

The main thing that Nick's proposal opens up is that if you have a local or global that you want to use as a value pattern, you can just prefix it with ==. For example:

RED = 1
GREEN = 2

def dispatch(color):
  match color:
    case ==RED: print("it's red!")
    case ==GREEN: print("it's green")
    case _: print("neither")

There are some situations where this would be nice to have, and our current best offer (something with a namespace) is much uglier than the == prefix.

Nick's grammar allows any primary after == or is, meaning you could also write things like this:

case ==(eval(open(fn).read())

That doesn't bother me tremendously.

If we could convince Nick to default True and False to is as well, this would be an open door that we could choose to enter later: we might not accept or implement PEP 642 now, but we could add the == and is prefixes later without any backwards incompatibilities.

There's a slight problem with == in class patterns, where we might end up with this:

case SomeClass(a===b):

This can be resolved in the tokenizer: if it sees three = signs in a row, it could tokenize this as = == instead of == =. Although to JavaScript eyes this will probably just be confusing.

gvanrossum commented 3 years ago

There's another big rewrite if PEP 642. I don't think we need to worry much about it; I'm opening one new issue about a thing we might possibly consider.