|
|
Log in / Subscribe / Register

"Structural pattern matching" for Python, part 2

"Structural pattern matching" for Python, part 2

Posted Sep 15, 2020 13:28 UTC (Tue) by udifuchs (guest, #141354)
Parent article: "Structural pattern matching" for Python, part 2

The syntax that I find confusing is the class pattern matching:

match pt:
case Point2D(x, y):

It looks like the class is being initiated.
I was wondering if using square brackets would make more sense,
as it is similar to the syntax used for type annotations.
For example:

match pt:
case Point2D[x, y]:

One issue with this idea is that the square bracket use might be confused with
item access. In enum, for example, this is a valid syntax:

>>> Sides["SPAM"] == Sides.SPAM == Sides("Spam")
True

Resolving this conflict would probably require not allowing such item access
inside a case statement.


to post comments

"Structural pattern matching" for Python, part 2

Posted Sep 16, 2020 15:59 UTC (Wed) by HelloWorld (guest, #56129) [Link] (1 responses)

> case Point2D(x, y):
>
> It looks like the class is being initiated.

No, it doesn't, because there is a case keyword right before it, it's pretty much impossible to miss. If the reader doesn't know what that means and starts making wild guesses, the problem isn't with the language but with the reader.

"Structural pattern matching" for Python, part 2

Posted Sep 18, 2020 4:23 UTC (Fri) by udifuchs (guest, #141354) [Link]

I know that a computer parser could easily understand this syntax. Still, as a human, I find it confusing. Most keywords in python are followed by an expression. The case keyword is followed by a pattern that has a syntax similar to an expression. This is confusing.

The PEP mentions that assignment targets in python also look like expressions, but this is true in a very narrow way. It is a syntax error to write 'int(x) = 3', while 'case int(x):' is valid.

More specifically, while reading the is_tuple() example in the PEP, it took me a while to realize that LParen() is initialized in the original code but not in the new code. If LParen.__init__() has some side effects, the two versions of the code that look very similar could be very different.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds