File: fix_operator.py

package info (click to toggle)
python2.6 2.6.8-1.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 65,740 kB
  • sloc: ansic: 389,342; python: 376,882; asm: 9,734; sh: 4,934; makefile: 4,040; lisp: 2,933; objc: 775; xml: 62
file content (40 lines) | stat: -rw-r--r-- 1,496 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""Fixer for operator.{isCallable,sequenceIncludes}

operator.isCallable(obj) -> hasattr(obj, '__call__')
operator.sequenceIncludes(obj) -> operator.contains(obj)
"""

# Local imports
from .. import fixer_base
from ..fixer_util import Call, Name, String

class FixOperator(fixer_base.BaseFix):

    methods = "method=('isCallable'|'sequenceIncludes')"
    func = "'(' func=any ')'"
    PATTERN = """
              power< module='operator'
                trailer< '.' %(methods)s > trailer< %(func)s > >
              |
              power< %(methods)s trailer< %(func)s > >
              """ % dict(methods=methods, func=func)

    def transform(self, node, results):
        method = results["method"][0]

        if method.value == u"sequenceIncludes":
            if "module" not in results:
                # operator may not be in scope, so we can't make a change.
                self.warning(node, "You should use operator.contains here.")
            else:
                method.value = u"contains"
                method.changed()
        elif method.value == u"isCallable":
            if "module" not in results:
                self.warning(node,
                             "You should use hasattr(%s, '__call__') here." %
                             results["func"].value)
            else:
                func = results["func"]
                args = [func.clone(), String(u", "), String(u"'__call__'")]
                return Call(Name(u"hasattr"), args, prefix=node.prefix)