1
# Copyright 2006 Google, Inc. All Rights Reserved.
2
# Licensed to PSF under a Contributor Agreement.
4
"""Fixer for has_key().
6
Calls to .has_key() methods are expressed in terms of the 'in'
12
1) While the primary target of this fixer is dict.has_key(), the
13
fixer will change any has_key() method call, regardless of its
16
2) Cases like this will not be converted:
22
Only *calls* to has_key() are converted. While it is possible to
23
convert the above to something like
29
this is currently not done.
34
from ..pgen2 import token
35
from .. import fixer_base
36
from ..fixer_util import Name, parenthesize
39
class FixHasKey(fixer_base.BaseFix):
44
trailer< '.' 'has_key' >
47
( not(arglist | argument<any '=' any>) arg=any
48
| arglist<(not argument<any '=' any>) arg=any ','>
59
trailer< '.' 'has_key' >
62
( not(arglist | argument<any '=' any>) arg=any
63
| arglist<(not argument<any '=' any>) arg=any ','>
71
def transform(self, node, results):
74
if (node.parent.type == syms.not_test and
75
self.pattern.match(node.parent)):
76
# Don't transform a node matching the first alternative of the
77
# pattern when its parent matches the second alternative
79
negation = results.get("negation")
80
anchor = results["anchor"]
81
prefix = node.get_prefix()
82
before = [n.clone() for n in results["before"]]
83
arg = results["arg"].clone()
84
after = results.get("after")
86
after = [n.clone() for n in after]
87
if arg.type in (syms.comparison, syms.not_test, syms.and_test,
88
syms.or_test, syms.test, syms.lambdef, syms.argument):
89
arg = parenthesize(arg)
93
before = pytree.Node(syms.power, before)
94
before.set_prefix(" ")
95
n_op = Name("in", prefix=" ")
97
n_not = Name("not", prefix=" ")
98
n_op = pytree.Node(syms.comp_op, (n_not, n_op))
99
new = pytree.Node(syms.comparison, (arg, n_op, before))
101
new = parenthesize(new)
102
new = pytree.Node(syms.power, (new,) + tuple(after))
103
if node.parent.type in (syms.comparison, syms.expr, syms.xor_expr,
104
syms.and_expr, syms.shift_expr,
105
syms.arith_expr, syms.term,
106
syms.factor, syms.power):
107
new = parenthesize(new)
108
new.set_prefix(prefix)