"Structural pattern matching" for Python, part 1
"Structural pattern matching" for Python, part 1
Posted Aug 5, 2020 22:27 UTC (Wed) by logang (subscriber, #127618)In reply to: "Structural pattern matching" for Python, part 1 by mb
Parent article: "Structural pattern matching" for Python, part 1
I agree. One of the things I liked about Python over Perl and Ruby is not having to parse some weird magic stuff like this.
The is_tuple() example is pretty clear for anyone vaguely familiar with programming. (It's also in lib2to3 code that should be pretty dead by now anyway). The match replacement is not clear: on first blush I'd expect it not to be equivalent and only match in cases that are far more specific. It's only saves a couple lines anyway.
Cleaning up the offending code itself would probably be a better idea. It's already very odd that the empty tuple case matches different LParen and RParen while the full tuple case allows for more general Leaf instances.
But something like this would probably be less tedious to read and not require nasty match syntax:
def is_tuple(node):
if not isinstance(node, Node) or not node.children:
return False
if node.children[0] != LParen() or node.children[-1] != RParen():
return False
if len(node.children) == 2:
return True # Empty Tuple
elif len(node.children) == 3:
return isinstance(node.children[1], Node)
else:
return False
The LWN site is currently under high scraper load, so comment display has been suppressed for anonymous users. If you are a human, you may read the comments by clicking the button below:
Note: you can avoid this step in the future by logging into your LWN account.
