Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b821173

Browse files
corona10vstinner
authored andcommitted
bpo-38871: Fix lib2to3 for filter-based statements that contain lambda (GH-17780)
Correctly parenthesize filter-based statements that contain lambda expressions in lib2to3.
1 parent 13a7ee8 commit b821173

3 files changed

Lines changed: 14 additions & 3 deletions

File tree

Lib/lib2to3/fixes/fix_filter.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from .. import fixer_base
1818
from ..pytree import Node
1919
from ..pygram import python_symbols as syms
20-
from ..fixer_util import Name, ArgList, ListComp, in_special_context
20+
from ..fixer_util import Name, ArgList, ListComp, in_special_context, parenthesize
2121

2222

2323
class FixFilter(fixer_base.ConditionalFix):
@@ -65,10 +65,14 @@ def transform(self, node, results):
6565
trailers.append(t.clone())
6666

6767
if "filter_lambda" in results:
68+
xp = results.get("xp").clone()
69+
if xp.type == syms.test:
70+
xp.prefix = ""
71+
xp = parenthesize(xp)
72+
6873
new = ListComp(results.get("fp").clone(),
6974
results.get("fp").clone(),
70-
results.get("it").clone(),
71-
results.get("xp").clone())
75+
results.get("it").clone(), xp)
7276
new = Node(syms.power, [new] + trailers, prefix="")
7377

7478
elif "none" in results:

Lib/lib2to3/tests/test_fixers.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2954,6 +2954,11 @@ def test_filter_basic(self):
29542954
a = """x = [x for x in range(10) if x%2 == 0]"""
29552955
self.check(b, a)
29562956

2957+
# bpo-38871
2958+
b = """filter(lambda x: True if x > 2 else False, [1, 2, 3])"""
2959+
a = """[x for x in [1, 2, 3] if (True if x > 2 else False)]"""
2960+
self.check(b, a)
2961+
29572962
def test_filter_trailers(self):
29582963
b = """x = filter(None, 'abc')[0]"""
29592964
a = """x = [_f for _f in 'abc' if _f][0]"""
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Correctly parenthesize filter-based statements that contain lambda
2+
expressions in mod:`lib2to3`. Patch by Dong-hee Na.

0 commit comments

Comments
 (0)