PageRenderTime 398ms CodeModel.GetById 169ms app.highlight 5ms RepoModel.GetById 128ms app.codeStats 0ms

/Lib/lib2to3/fixes/fix_filter.py

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