Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions Lib/lib2to3/fixes/fix_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from .. import fixer_base
from ..pytree import Node
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):
Expand Down Expand Up @@ -65,10 +65,14 @@ def transform(self, node, results):
trailers.append(t.clone())

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(),
results.get("fp").clone(),
results.get("it").clone(),
results.get("xp").clone())
results.get("it").clone(), xp)
new = Node(syms.power, [new] + trailers, prefix="")

elif "none" in results:
Expand Down
5 changes: 5 additions & 0 deletions Lib/lib2to3/tests/test_fixers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2954,6 +2954,11 @@ def test_filter_basic(self):
a = """x = [x for x in range(10) if x%2 == 0]"""
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):
b = """x = filter(None, 'abc')[0]"""
a = """x = [_f for _f in 'abc' if _f][0]"""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Correctly parenthesize filter-based statements that contain lambda
expressions in mod:`lib2to3`. Patch by Dong-hee Na.