108
107
if not hasattr(self, 'funcname'):
109
108
raise exceptions.CompileException(
110
"Code '%s' is not a function declaration" % code,
109
"Code '%s' is not a function declaration" % code,
112
111
if not allow_kwargs and self.kwargs:
113
112
raise exceptions.CompileException(
114
113
"'**%s' keyword argument not allowed here" %
115
self.argnames[-1], **exception_kwargs)
117
def get_argument_expressions(self, include_defaults=True):
118
"""return the argument declarations of this FunctionDecl as a printable
114
self.kwargnames[-1], **exception_kwargs)
116
def get_argument_expressions(self, as_call=False):
117
"""Return the argument declarations of this FunctionDecl as a printable
120
By default the return value is appropriate for writing in a ``def``;
121
set `as_call` to true to build arguments to be passed to the function
122
instead (assuming locals with the same names as the arguments exist).
122
defaults = [d for d in self.defaults]
124
varargs = self.varargs
125
argnames = [f for f in self.argnames]
130
arg = "**" + arg_stringname(arg)
133
arg = "*" + arg_stringname(arg)
136
default = len(defaults) and defaults.pop() or None
137
if include_defaults and default:
138
namedecls.insert(0, "%s=%s" %
140
pyparser.ExpressionGenerator(default).value()
144
namedecls.insert(0, arg)
127
# Build in reverse order, since defaults and slurpy args come last
128
argnames = self.argnames[::-1]
129
kwargnames = self.kwargnames[::-1]
130
defaults = self.defaults[::-1]
131
kwdefaults = self.kwdefaults[::-1]
135
namedecls.append("**" + kwargnames.pop(0))
137
for name in kwargnames:
138
# Keyword-only arguments must always be used by name, so even if
139
# this is a call, print out `foo=foo`
141
namedecls.append("%s=%s" % (name, name))
143
default = kwdefaults.pop(0)
145
# The AST always gives kwargs a default, since you can do
146
# `def foo(*, a=1, b, c=3)`
147
namedecls.append(name)
149
namedecls.append("%s=%s" % (
150
name, pyparser.ExpressionGenerator(default).value()))
152
namedecls.append(name)
154
# Positional arguments
156
namedecls.append("*" + argnames.pop(0))
158
for name in argnames:
159
if as_call or not defaults:
160
namedecls.append(name)
162
default = defaults.pop(0)
163
namedecls.append("%s=%s" % (
164
name, pyparser.ExpressionGenerator(default).value()))
170
def allargnames(self):
171
return tuple(self.argnames) + tuple(self.kwargnames)
147
173
class FunctionArgs(FunctionDecl):
148
174
"""the argument portion of a function declaration"""