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

Python code coverage for Lib/lib2to3/fixes/fix_map.py

#countcontent
1n/a# Copyright 2007 Google, Inc. All Rights Reserved.
2n/a# Licensed to PSF under a Contributor Agreement.
3n/a
4n/a"""Fixer that changes map(F, ...) into list(map(F, ...)) unless there
5n/aexists a 'from future_builtins import map' statement in the top-level
6n/anamespace.
7n/a
8n/aAs a special case, map(None, X) is changed into list(X). (This is
9n/anecessary because the semantics are changed in this case -- the new
10n/amap(None, X) is equivalent to [(x,) for x in X].)
11n/a
12n/aWe avoid the transformation (except for the special case mentioned
13n/aabove) if the map() call is directly contained in iter(<>), list(<>),
14n/atuple(<>), sorted(<>), ...join(<>), or for V in <>:.
15n/a
16n/aNOTE: This is still not correct if the original code was depending on
17n/amap(F, X, Y, ...) to go on until the longest argument is exhausted,
18n/asubstituting None for missing values -- like zip(), it now stops as
19n/asoon as the shortest argument is exhausted.
20n/a"""
21n/a
22n/a# Local imports
23n/afrom ..pgen2 import token
24n/afrom .. import fixer_base
25n/afrom ..fixer_util import Name, Call, ListComp, in_special_context
26n/afrom ..pygram import python_symbols as syms
27n/a
28n/aclass FixMap(fixer_base.ConditionalFix):
29n/a BM_compatible = True
30n/a
31n/a PATTERN = """
32n/a map_none=power<
33n/a 'map'
34n/a trailer< '(' arglist< 'None' ',' arg=any [','] > ')' >
35n/a >
36n/a |
37n/a map_lambda=power<
38n/a 'map'
39n/a trailer<
40n/a '('
41n/a arglist<
42n/a lambdef< 'lambda'
43n/a (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any
44n/a >
45n/a ','
46n/a it=any
47n/a >
48n/a ')'
49n/a >
50n/a >
51n/a |
52n/a power<
53n/a 'map' trailer< '(' [arglist=any] ')' >
54n/a >
55n/a """
56n/a
57n/a skip_on = 'future_builtins.map'
58n/a
59n/a def transform(self, node, results):
60n/a if self.should_skip(node):
61n/a return
62n/a
63n/a if node.parent.type == syms.simple_stmt:
64n/a self.warning(node, "You should use a for loop here")
65n/a new = node.clone()
66n/a new.prefix = ""
67n/a new = Call(Name("list"), [new])
68n/a elif "map_lambda" in results:
69n/a new = ListComp(results["xp"].clone(),
70n/a results["fp"].clone(),
71n/a results["it"].clone())
72n/a else:
73n/a if "map_none" in results:
74n/a new = results["arg"].clone()
75n/a else:
76n/a if "arglist" in results:
77n/a args = results["arglist"]
78n/a if args.type == syms.arglist and \
79n/a args.children[0].type == token.NAME and \
80n/a args.children[0].value == "None":
81n/a self.warning(node, "cannot convert map(None, ...) "
82n/a "with multiple arguments because map() "
83n/a "now truncates to the shortest sequence")
84n/a return
85n/a if in_special_context(node):
86n/a return None
87n/a new = node.clone()
88n/a new.prefix = ""
89n/a new = Call(Name("list"), [new])
90n/a new.prefix = node.prefix
91n/a return new