Fix the tag.
[python/dscho.git] / Lib / lib2to3 / fixes / fix_idioms.py
blob2ca2a834271d58713214347f288f06f3864baac7
1 """Adjust some old Python 2 idioms to their modern counterparts.
3 * Change some type comparisons to isinstance() calls:
4 type(x) == T -> isinstance(x, T)
5 type(x) is T -> isinstance(x, T)
6 type(x) != T -> not isinstance(x, T)
7 type(x) is not T -> not isinstance(x, T)
9 * Change "while 1:" into "while True:".
11 * Change both
13 v = list(EXPR)
14 v.sort()
15 foo(v)
17 and the more general
19 v = EXPR
20 v.sort()
21 foo(v)
23 into
25 v = sorted(EXPR)
26 foo(v)
27 """
28 # Author: Jacques Frechet, Collin Winter
30 # Local imports
31 from . import basefix
32 from .util import Call, Comma, Name, Node, syms
34 CMP = "(n='!=' | '==' | 'is' | n=comp_op< 'is' 'not' >)"
35 TYPE = "power< 'type' trailer< '(' x=any ')' > >"
37 class FixIdioms(basefix.BaseFix):
39 explicit = True # The user must ask for this fixer
41 PATTERN = r"""
42 isinstance=comparison< %s %s T=any >
44 isinstance=comparison< T=any %s %s >
46 while_stmt< 'while' while='1' ':' any+ >
48 sorted=any<
49 any*
50 simple_stmt<
51 expr_stmt< id1=any '='
52 power< list='list' trailer< '(' (not arglist<any+>) any ')' > >
54 '\n'
56 sort=
57 simple_stmt<
58 power< id2=any
59 trailer< '.' 'sort' > trailer< '(' ')' >
61 '\n'
63 next=any*
66 sorted=any<
67 any*
68 simple_stmt< expr_stmt< id1=any '=' expr=any > '\n' >
69 sort=
70 simple_stmt<
71 power< id2=any
72 trailer< '.' 'sort' > trailer< '(' ')' >
74 '\n'
76 next=any*
78 """ % (TYPE, CMP, CMP, TYPE)
80 def match(self, node):
81 r = super(FixIdioms, self).match(node)
82 # If we've matched one of the sort/sorted subpatterns above, we
83 # want to reject matches where the initial assignment and the
84 # subsequent .sort() call involve different identifiers.
85 if r and "sorted" in r:
86 if r["id1"] == r["id2"]:
87 return r
88 return None
89 return r
91 def transform(self, node, results):
92 if "isinstance" in results:
93 return self.transform_isinstance(node, results)
94 elif "while" in results:
95 return self.transform_while(node, results)
96 elif "sorted" in results:
97 return self.transform_sort(node, results)
98 else:
99 raise RuntimeError("Invalid match")
101 def transform_isinstance(self, node, results):
102 x = results["x"].clone() # The thing inside of type()
103 T = results["T"].clone() # The type being compared against
104 x.set_prefix("")
105 T.set_prefix(" ")
106 test = Call(Name("isinstance"), [x, Comma(), T])
107 if "n" in results:
108 test.set_prefix(" ")
109 test = Node(syms.not_test, [Name("not"), test])
110 test.set_prefix(node.get_prefix())
111 return test
113 def transform_while(self, node, results):
114 one = results["while"]
115 one.replace(Name("True", prefix=one.get_prefix()))
117 def transform_sort(self, node, results):
118 sort_stmt = results["sort"]
119 next_stmt = results["next"]
120 list_call = results.get("list")
121 simple_expr = results.get("expr")
123 if list_call:
124 list_call.replace(Name("sorted", prefix=list_call.get_prefix()))
125 elif simple_expr:
126 new = simple_expr.clone()
127 new.set_prefix("")
128 simple_expr.replace(Call(Name("sorted"), [new],
129 prefix=simple_expr.get_prefix()))
130 else:
131 raise RuntimeError("should not have reached here")
132 sort_stmt.remove()
133 if next_stmt:
134 next_stmt[0].set_prefix(sort_stmt.get_prefix())