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:".
28 # Author: Jacques Frechet, Collin Winter
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
42 isinstance=comparison< %s %s T=any >
44 isinstance=comparison< T=any %s %s >
46 while_stmt< 'while' while='1' ':' any+ >
51 expr_stmt< id1=any '='
52 power< list='list' trailer< '(' (not arglist<any+>) any ')' > >
59 trailer< '.' 'sort' > trailer< '(' ')' >
68 simple_stmt< expr_stmt< id1=any '=' expr=any > '\n' >
72 trailer< '.' 'sort' > trailer< '(' ')' >
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"]:
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
)
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
106 test
= Call(Name("isinstance"), [x
, Comma(), T
])
109 test
= Node(syms
.not_test
, [Name("not"), test
])
110 test
.set_prefix(node
.get_prefix())
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")
124 list_call
.replace(Name("sorted", prefix
=list_call
.get_prefix()))
126 new
= simple_expr
.clone()
128 simple_expr
.replace(Call(Name("sorted"), [new
],
129 prefix
=simple_expr
.get_prefix()))
131 raise RuntimeError("should not have reached here")
134 next_stmt
[0].set_prefix(sort_stmt
.get_prefix())