Skip to content

Commit

Permalink
Fix transformation of non-iter dict methods in for loops
Browse files Browse the repository at this point in the history
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()`.
  • Loading branch information
takluyver committed Mar 20, 2015
1 parent 5ab6f01 commit 8a1ef24
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions libmodernize/fixes/fix_dict_six.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,9 @@ def transform(self, node, results):
return super(FixDictSix, self).transform(node, results)
else:
return self.transform_iter(method_name, node, results['head'])

def in_special_context(self, node, isiter):
# Redefined from parent class to make "for x in d.items()" count as
# in special context; 2to3 only counts for loops as special context
# for the iter* methods.
return super(FixDictSix, self).in_special_context(node, True)
11 changes: 11 additions & 0 deletions tests/test_fix_dict_six.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@
list(x.{type}())
""")

DICT_IN_LOOP = ("""\
for k in x.items():
pass
""", """\
for k in x.items():
pass
""")


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

def test_dict_plain():
check_all_types(*DICT_PLAIN)

def test_dict_in_loop():
check_on_input(*DICT_IN_LOOP)

0 comments on commit 8a1ef24

Please sign in to comment.