Skip to content

Commit 8a1ef24

Browse files
committed
Fix transformation of non-iter dict methods in for loops
Addresses issue #119 - it's not exactly what the author asked for, but I think it's better ;-) For some reason, 2to3 only treats a for loop as a special context for iter* methods, so it will add a list() call to e.g. `for x in d.values()`.
1 parent 5ab6f01 commit 8a1ef24

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

libmodernize/fixes/fix_dict_six.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,9 @@ def transform(self, node, results):
2424
return super(FixDictSix, self).transform(node, results)
2525
else:
2626
return self.transform_iter(method_name, node, results['head'])
27+
28+
def in_special_context(self, node, isiter):
29+
# Redefined from parent class to make "for x in d.items()" count as
30+
# in special context; 2to3 only counts for loops as special context
31+
# for the iter* methods.
32+
return super(FixDictSix, self).in_special_context(node, True)

tests/test_fix_dict_six.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@
2727
list(x.{type}())
2828
""")
2929

30+
DICT_IN_LOOP = ("""\
31+
for k in x.items():
32+
pass
33+
""", """\
34+
for k in x.items():
35+
pass
36+
""")
37+
3038

3139
def check_all_types(input, output):
3240
for type_ in TYPES:
@@ -40,3 +48,6 @@ def test_dict_view():
4048

4149
def test_dict_plain():
4250
check_all_types(*DICT_PLAIN)
51+
52+
def test_dict_in_loop():
53+
check_on_input(*DICT_IN_LOOP)

0 commit comments

Comments
 (0)