For your consideration: PEP 845, with the following abstract:
This PEP enables the use of non-attribute names as value patterns in match statements. A name prefixed with a dot is looked up using the normal name resolution rules and compared to the match subject by equality in the same manner as existing value patterns, instead of being treated as a capture pattern. This makes it possible to match local variables and global variables defined in the same module without using a guard clause.
def get_book_titles_for_author(author: str):
for book in BOOKS:
match book:
case {"title": title, "author": .author}:
yield title
Not exactly sure what you’re referring to. Would you mind posting a small example? That might help me better understand what you’re getting at. Feel free to also try out the online demo linked above.
I don’t think that will work. The match statement mini-syntax doesn’t support [ ]. Even ( ) isn’t recognized as a function call but an isinstance check instead. So we’d first have to define what [ ] means for pattern matching.
This looks like a good solution to this problem. I have had to work around this issue, in one case introducing a wrapping object just so that I could match it with box.value.
I don’t know how intuitive this syntax is for me. It kinda looks like you try to match an object that has an author attribute. (Like some sort of an inline Protocol).
That’s not possible. Name captures are only assigned after the pattern itself matched (but before the guard is evaluated). Therefore your example would raise an error.
>>> match [1, 1]:
... case [x, *_, .x]:
... pass
...
Traceback (most recent call last):
File "<python-input-8>", line 2, in <module>
case [x, *_, .x]:
^
NameError: name 'x' is not defined