bpo-38871: Fix lib2to3 for filter-based statements that contain lambda (GH-17780)

Correctly parenthesize filter-based statements that contain lambda
expressions in lib2to3.
This commit is contained in:
Dong-hee Na 2020-01-08 02:30:55 +09:00 committed by Victor Stinner
parent 13a7ee8d62
commit b821173b54
3 changed files with 14 additions and 3 deletions

View File

@ -17,7 +17,7 @@ Python 2.6 figure it out.
from .. import fixer_base from .. import fixer_base
from ..pytree import Node from ..pytree import Node
from ..pygram import python_symbols as syms from ..pygram import python_symbols as syms
from ..fixer_util import Name, ArgList, ListComp, in_special_context from ..fixer_util import Name, ArgList, ListComp, in_special_context, parenthesize
class FixFilter(fixer_base.ConditionalFix): class FixFilter(fixer_base.ConditionalFix):
@ -65,10 +65,14 @@ class FixFilter(fixer_base.ConditionalFix):
trailers.append(t.clone()) trailers.append(t.clone())
if "filter_lambda" in results: if "filter_lambda" in results:
xp = results.get("xp").clone()
if xp.type == syms.test:
xp.prefix = ""
xp = parenthesize(xp)
new = ListComp(results.get("fp").clone(), new = ListComp(results.get("fp").clone(),
results.get("fp").clone(), results.get("fp").clone(),
results.get("it").clone(), results.get("it").clone(), xp)
results.get("xp").clone())
new = Node(syms.power, [new] + trailers, prefix="") new = Node(syms.power, [new] + trailers, prefix="")
elif "none" in results: elif "none" in results:

View File

@ -2954,6 +2954,11 @@ class Test_filter(FixerTestCase):
a = """x = [x for x in range(10) if x%2 == 0]""" a = """x = [x for x in range(10) if x%2 == 0]"""
self.check(b, a) self.check(b, a)
# bpo-38871
b = """filter(lambda x: True if x > 2 else False, [1, 2, 3])"""
a = """[x for x in [1, 2, 3] if (True if x > 2 else False)]"""
self.check(b, a)
def test_filter_trailers(self): def test_filter_trailers(self):
b = """x = filter(None, 'abc')[0]""" b = """x = filter(None, 'abc')[0]"""
a = """x = [_f for _f in 'abc' if _f][0]""" a = """x = [_f for _f in 'abc' if _f][0]"""

View File

@ -0,0 +1,2 @@
Correctly parenthesize filter-based statements that contain lambda
expressions in mod:`lib2to3`. Patch by Dong-hee Na.