1 | n/a | # Copyright 2007 Google, Inc. All Rights Reserved. |
---|
2 | n/a | # Licensed to PSF under a Contributor Agreement. |
---|
3 | n/a | |
---|
4 | n/a | """Fixer that changes filter(F, X) into list(filter(F, X)). |
---|
5 | n/a | |
---|
6 | n/a | We avoid the transformation if the filter() call is directly contained |
---|
7 | n/a | in iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or |
---|
8 | n/a | for V in <>:. |
---|
9 | n/a | |
---|
10 | n/a | NOTE: This is still not correct if the original code was depending on |
---|
11 | n/a | filter(F, X) to return a string if X is a string and a tuple if X is a |
---|
12 | n/a | tuple. That would require type inference, which we don't do. Let |
---|
13 | n/a | Python 2.6 figure it out. |
---|
14 | n/a | """ |
---|
15 | n/a | |
---|
16 | n/a | # Local imports |
---|
17 | n/a | from .. import fixer_base |
---|
18 | n/a | from ..fixer_util import Name, Call, ListComp, in_special_context |
---|
19 | n/a | |
---|
20 | n/a | class FixFilter(fixer_base.ConditionalFix): |
---|
21 | n/a | BM_compatible = True |
---|
22 | n/a | |
---|
23 | n/a | PATTERN = """ |
---|
24 | n/a | filter_lambda=power< |
---|
25 | n/a | 'filter' |
---|
26 | n/a | trailer< |
---|
27 | n/a | '(' |
---|
28 | n/a | arglist< |
---|
29 | n/a | lambdef< 'lambda' |
---|
30 | n/a | (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any |
---|
31 | n/a | > |
---|
32 | n/a | ',' |
---|
33 | n/a | it=any |
---|
34 | n/a | > |
---|
35 | n/a | ')' |
---|
36 | n/a | > |
---|
37 | n/a | > |
---|
38 | n/a | | |
---|
39 | n/a | power< |
---|
40 | n/a | 'filter' |
---|
41 | n/a | trailer< '(' arglist< none='None' ',' seq=any > ')' > |
---|
42 | n/a | > |
---|
43 | n/a | | |
---|
44 | n/a | power< |
---|
45 | n/a | 'filter' |
---|
46 | n/a | args=trailer< '(' [any] ')' > |
---|
47 | n/a | > |
---|
48 | n/a | """ |
---|
49 | n/a | |
---|
50 | n/a | skip_on = "future_builtins.filter" |
---|
51 | n/a | |
---|
52 | n/a | def transform(self, node, results): |
---|
53 | n/a | if self.should_skip(node): |
---|
54 | n/a | return |
---|
55 | n/a | |
---|
56 | n/a | if "filter_lambda" in results: |
---|
57 | n/a | new = ListComp(results.get("fp").clone(), |
---|
58 | n/a | results.get("fp").clone(), |
---|
59 | n/a | results.get("it").clone(), |
---|
60 | n/a | results.get("xp").clone()) |
---|
61 | n/a | |
---|
62 | n/a | elif "none" in results: |
---|
63 | n/a | new = ListComp(Name("_f"), |
---|
64 | n/a | Name("_f"), |
---|
65 | n/a | results["seq"].clone(), |
---|
66 | n/a | Name("_f")) |
---|
67 | n/a | |
---|
68 | n/a | else: |
---|
69 | n/a | if in_special_context(node): |
---|
70 | n/a | return None |
---|
71 | n/a | new = node.clone() |
---|
72 | n/a | new.prefix = "" |
---|
73 | n/a | new = Call(Name("list"), [new]) |
---|
74 | n/a | new.prefix = node.prefix |
---|
75 | n/a | return new |
---|