Implimenting issue #887 - Adding an optional if or for at the end of a comp function. #901
Implimenting issue #887 - Adding an optional if or for at the end of a comp function. #901ad4mf06 wants to merge 2 commits intoevhub:developfrom
Conversation
|
I think it's a bit confusing for only the first comprehension to have the ability to be a pattern-matching comprehension. My preference here is to either stick with the current implementation that only allows one comprehension, or to support arbitrary mixing and matching of standard and pattern-matching comprehensions (the ideal, but annoying to implement). |
…matching comprehensions
|
Thanks for the feedback! I've updated the PR to implement the ideal option — arbitrary mixing and matching of standard and pattern-matching comprehensions. The approach works by adding two new grammar rules (inner_match_comp_for with explicit match keyword, and implicit_inner_match_comp_for without) to comp_iter, which is the recursive clause rule. This means pattern-matching for |
Summary
This PR implements issue #887 by adding support for optional
ifandforclauses at the end of pattern-matching comprehensions.Changes
grammar.py(line 1969)Added
.Optional(comp_iter)at the end ofmatch_comp_for, allowing an optionaliforforclause to be appended to a pattern-matching comprehension.compiler.py(line 4597)Modified the
match_comp_expr_handlefunction to handle the optional extra comprehension clauses:len(match_for_group) == 2: the group contains onlymatchesanditerable(no extra clauses).len(match_for_group) > 2: the third element and beyond are joined intoextra_comp_clauses, which are appended to the generated Python comprehension expression.Extra clauses are also handled for
expr_setnamescontext: any variables introduced byforclauses inextra_comp_clausesare extracted via regex and removed fromnew_namesto avoid false positives in scope analysis.tests/src/cocotest/agnostic/primary_2.cocoAdded a comprehensive test suite for pattern-matching comprehensions covering:
CompPairandCompTripledata typesforclauses after the pattern matchfor+ifcombinations on loop variablesiffiltering on pattern variables (single and multiple conditions)and