1# Copyright 2006 Google, Inc. All Rights Reserved. 2# Licensed to PSF under a Contributor Agreement. 3 4"""Fixer for apply(). 5 6This converts apply(func, v, k) into (func)(*v, **k).""" 7 8# Local imports 9from .. import pytree 10from ..pgen2 import token 11from .. import fixer_base 12from ..fixer_util import Call, Comma, parenthesize 13 14class FixApply(fixer_base.BaseFix): 15 BM_compatible = True 16 17 PATTERN = """ 18 power< 'apply' 19 trailer< 20 '(' 21 arglist< 22 (not argument<NAME '=' any>) func=any ',' 23 (not argument<NAME '=' any>) args=any [',' 24 (not argument<NAME '=' any>) kwds=any] [','] 25 > 26 ')' 27 > 28 > 29 """ 30 31 def transform(self, node, results): 32 syms = self.syms 33 assert results 34 func = results["func"] 35 args = results["args"] 36 kwds = results.get("kwds") 37 # I feel like we should be able to express this logic in the 38 # PATTERN above but I don't know how to do it so... 39 if args: 40 if (args.type == self.syms.argument and 41 args.children[0].value in {'**', '*'}): 42 return # Make no change. 43 if kwds and (kwds.type == self.syms.argument and 44 kwds.children[0].value == '**'): 45 return # Make no change. 46 prefix = node.prefix 47 func = func.clone() 48 if (func.type not in (token.NAME, syms.atom) and 49 (func.type != syms.power or 50 func.children[-2].type == token.DOUBLESTAR)): 51 # Need to parenthesize 52 func = parenthesize(func) 53 func.prefix = "" 54 args = args.clone() 55 args.prefix = "" 56 if kwds is not None: 57 kwds = kwds.clone() 58 kwds.prefix = "" 59 l_newargs = [pytree.Leaf(token.STAR, "*"), args] 60 if kwds is not None: 61 l_newargs.extend([Comma(), 62 pytree.Leaf(token.DOUBLESTAR, "**"), 63 kwds]) 64 l_newargs[-2].prefix = " " # that's the ** token 65 # XXX Sometimes we could be cleverer, e.g. apply(f, (x, y) + t) 66 # can be translated into f(x, y, *t) instead of f(*(x, y) + t) 67 #new = pytree.Node(syms.power, (func, ArgList(l_newargs))) 68 return Call(func, l_newargs, prefix=prefix) 69