+++ /dev/null
-# Copyright 2006 Google, Inc. All Rights Reserved.\r
-# Licensed to PSF under a Contributor Agreement.\r
-\r
-"""Fixer for has_key().\r
-\r
-Calls to .has_key() methods are expressed in terms of the 'in'\r
-operator:\r
-\r
- d.has_key(k) -> k in d\r
-\r
-CAVEATS:\r
-1) While the primary target of this fixer is dict.has_key(), the\r
- fixer will change any has_key() method call, regardless of its\r
- class.\r
-\r
-2) Cases like this will not be converted:\r
-\r
- m = d.has_key\r
- if m(k):\r
- ...\r
-\r
- Only *calls* to has_key() are converted. While it is possible to\r
- convert the above to something like\r
-\r
- m = d.__contains__\r
- if m(k):\r
- ...\r
-\r
- this is currently not done.\r
-"""\r
-\r
-# Local imports\r
-from .. import pytree\r
-from ..pgen2 import token\r
-from .. import fixer_base\r
-from ..fixer_util import Name, parenthesize\r
-\r
-\r
-class FixHasKey(fixer_base.BaseFix):\r
- BM_compatible = True\r
-\r
- PATTERN = """\r
- anchor=power<\r
- before=any+\r
- trailer< '.' 'has_key' >\r
- trailer<\r
- '('\r
- ( not(arglist | argument<any '=' any>) arg=any\r
- | arglist<(not argument<any '=' any>) arg=any ','>\r
- )\r
- ')'\r
- >\r
- after=any*\r
- >\r
- |\r
- negation=not_test<\r
- 'not'\r
- anchor=power<\r
- before=any+\r
- trailer< '.' 'has_key' >\r
- trailer<\r
- '('\r
- ( not(arglist | argument<any '=' any>) arg=any\r
- | arglist<(not argument<any '=' any>) arg=any ','>\r
- )\r
- ')'\r
- >\r
- >\r
- >\r
- """\r
-\r
- def transform(self, node, results):\r
- assert results\r
- syms = self.syms\r
- if (node.parent.type == syms.not_test and\r
- self.pattern.match(node.parent)):\r
- # Don't transform a node matching the first alternative of the\r
- # pattern when its parent matches the second alternative\r
- return None\r
- negation = results.get("negation")\r
- anchor = results["anchor"]\r
- prefix = node.prefix\r
- before = [n.clone() for n in results["before"]]\r
- arg = results["arg"].clone()\r
- after = results.get("after")\r
- if after:\r
- after = [n.clone() for n in after]\r
- if arg.type in (syms.comparison, syms.not_test, syms.and_test,\r
- syms.or_test, syms.test, syms.lambdef, syms.argument):\r
- arg = parenthesize(arg)\r
- if len(before) == 1:\r
- before = before[0]\r
- else:\r
- before = pytree.Node(syms.power, before)\r
- before.prefix = u" "\r
- n_op = Name(u"in", prefix=u" ")\r
- if negation:\r
- n_not = Name(u"not", prefix=u" ")\r
- n_op = pytree.Node(syms.comp_op, (n_not, n_op))\r
- new = pytree.Node(syms.comparison, (arg, n_op, before))\r
- if after:\r
- new = parenthesize(new)\r
- new = pytree.Node(syms.power, (new,) + tuple(after))\r
- if node.parent.type in (syms.comparison, syms.expr, syms.xor_expr,\r
- syms.and_expr, syms.shift_expr,\r
- syms.arith_expr, syms.term,\r
- syms.factor, syms.power):\r
- new = parenthesize(new)\r
- new.prefix = prefix\r
- return new\r