ยปCore Development>Code coverage>Lib/lib2to3/fixes/fix_xrange.py

# Python code coverage for Lib/lib2to3/fixes/fix_xrange.py

#countcontent
2n/a# Licensed to PSF under a Contributor Agreement.
3n/a
4n/a"""Fixer that changes xrange(...) into range(...)."""
5n/a
6n/a# Local imports
7n/afrom .. import fixer_base
8n/afrom ..fixer_util import Name, Call, consuming_calls
9n/afrom .. import patcomp
10n/a
11n/a
12n/aclass FixXrange(fixer_base.BaseFix):
13n/a BM_compatible = True
14n/a PATTERN = """
15n/a power<
16n/a (name='range'|name='xrange') trailer< '(' args=any ')' >
17n/a rest=any* >
18n/a """
19n/a
20n/a def start_tree(self, tree, filename):
21n/a super(FixXrange, self).start_tree(tree, filename)
22n/a self.transformed_xranges = set()
23n/a
24n/a def finish_tree(self, tree, filename):
25n/a self.transformed_xranges = None
26n/a
27n/a def transform(self, node, results):
28n/a name = results["name"]
29n/a if name.value == "xrange":
30n/a return self.transform_xrange(node, results)
31n/a elif name.value == "range":
32n/a return self.transform_range(node, results)
33n/a else:
34n/a raise ValueError(repr(name))
35n/a
36n/a def transform_xrange(self, node, results):
37n/a name = results["name"]
38n/a name.replace(Name("range", prefix=name.prefix))
39n/a # This prevents the new range call from being wrapped in a list later.
41n/a
42n/a def transform_range(self, node, results):
43n/a if (id(node) not in self.transformed_xranges and
44n/a not self.in_special_context(node)):
45n/a range_call = Call(Name("range"), [results["args"].clone()])
46n/a # Encase the range call in list().
47n/a list_call = Call(Name("list"), [range_call],
48n/a prefix=node.prefix)
49n/a # Put things that were after the range() call after the list call.
50n/a for n in results["rest"]:
51n/a list_call.append_child(n)
52n/a return list_call
53n/a
54n/a P1 = "power< func=NAME trailer< '(' node=any ')' > any* >"
55n/a p1 = patcomp.compile_pattern(P1)
56n/a
57n/a P2 = """for_stmt< 'for' any 'in' node=any ':' any* >
58n/a | comp_for< 'for' any 'in' node=any any* >
59n/a | comparison< any 'in' node=any any*>
60n/a """
61n/a p2 = patcomp.compile_pattern(P2)
62n/a
63n/a def in_special_context(self, node):
64n/a if node.parent is None:
65n/a return False
66n/a results = {}
67n/a if (node.parent.parent is not None and
68n/a self.p1.match(node.parent.parent, results) and
69n/a results["node"] is node):
70n/a # list(d.keys()) -> list(d.keys()), etc.
71n/a return results["func"].value in consuming_calls
72n/a # for ... in d.iterkeys() -> for ... in d.keys(), etc.
73n/a return self.p2.match(node.parent, results) and results["node"] is node