Skip to content

Commit 9599d29

Browse files
committed
Merge pull request #71 from brettcannon/fix_dict
Use lib2to3's fix_dict to help with list(dict.items())
2 parents f37a87e + 1787567 commit 9599d29

File tree

5 files changed

+67
-67
lines changed

5 files changed

+67
-67
lines changed

libmodernize/fixes/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
# fixes that involve using six
3030
six_fix_names = set([
3131
'libmodernize.fixes.fix_basestring',
32-
'libmodernize.fixes.fix_dict',
32+
'libmodernize.fixes.fix_dict_six',
3333
'libmodernize.fixes.fix_filter',
3434
'libmodernize.fixes.fix_input_six',
3535
'libmodernize.fixes.fix_map',

libmodernize/fixes/fix_dict.py

Lines changed: 0 additions & 25 deletions
This file was deleted.

libmodernize/fixes/fix_dict_six.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""Fixer for iterkeys() -> six.iterkeys(), and similarly for iteritems and itervalues."""
2+
3+
# Local imports
4+
from lib2to3 import fixer_base
5+
from lib2to3 import fixer_util
6+
from lib2to3 import patcomp
7+
from lib2to3.fixes import fix_dict
8+
9+
10+
class FixDictSix(fix_dict.FixDict):
11+
12+
def transform_iter(self, method_name, node, base):
13+
"""Call six.iteritems() and friends."""
14+
if method_name.startswith(u'view'):
15+
method_name = u'iter' + method_name[4:]
16+
fixer_util.touch_import(None, u'six', node)
17+
new_node = [n.clone() for n in base]
18+
new_node[0].prefix = u''
19+
name = fixer_util.Name(u'six.' + method_name, prefix=node.prefix)
20+
node.replace(fixer_util.Call(name, new_node))
21+
22+
def transform(self, node, results):
23+
method = results['method'][0]
24+
method_name = method.value
25+
if method_name in ('keys', 'items', 'values'):
26+
return super(FixDictSix, self).transform(node, results)
27+
else:
28+
return self.transform_iter(method_name, node, results['head'])

tests/test_fix_dict.py

Lines changed: 0 additions & 41 deletions
This file was deleted.

tests/test_fix_dict_six.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from utils import check_on_input
2+
3+
4+
TYPES = 'keys', 'items', 'values'
5+
6+
DICT_ITER = ("""\
7+
x.iter{type}()
8+
""", """\
9+
import six
10+
six.iter{type}(x)
11+
""")
12+
13+
DICT_VIEW = ("""\
14+
x.view{type}()
15+
""", """\
16+
import six
17+
six.iter{type}(x)
18+
""")
19+
20+
DICT_PLAIN = ("""\
21+
x.{type}()
22+
""", """\
23+
list(x.{type}())
24+
""")
25+
26+
27+
def check_all_types(input, output):
28+
for type_ in TYPES:
29+
check_on_input(input.format(type=type_), output.format(type=type_))
30+
31+
def test_dict_iter():
32+
check_all_types(*DICT_ITER)
33+
34+
def test_dict_view():
35+
check_all_types(*DICT_VIEW)
36+
37+
def test_dict_plain():
38+
check_all_types(*DICT_PLAIN)

0 commit comments

Comments
 (0)