The ** operator ambiguous?
duncan.booth at invalid.invalid
Mon Jul 16 20:02:33 CEST 2007
Robert Dailey <rcdailey at gmail.com> wrote:
> However, I have no idea what the
> ** operator is here. I know that when you specify ** as a parameter in
> a function definition, it represents a dictionary of parameters passed
> in. However, in this example it is NOT being used in a function
> definition. It is being used when passing variables into a function.
> Can someone explain what this means? I looked in the documentation but
> I couldn't find anything.
It is in the documentation. Look in the reference manual section "5.3.4
> If the syntax "*expression" appears in the function call, "expression"
> must evaluate to a sequence. Elements from this sequence are treated
> as if they were additional positional arguments; if there are
> postional arguments x1,...,xN , and "expression" evaluates to a
> sequence y1,...,yM, this is equivalent to a call with M+N positional
> arguments x1,...,xN,y1,...,yM.
> A consequence of this is that although the "*expression" syntax
> appears after any keyword arguments, it is processed before the
> keyword arguments (and the "**expression" argument, if any - see
> below). So:
>>>> def f(a, b):
> ... print a, b
>>>> f(b=1, *(2,))
> 2 1
>>>> f(a=1, *(2,))
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: f() got multiple values for keyword argument 'a'
>>>> f(1, *(2,))
> 1 2
> It is unusual for both keyword arguments and the "*expression" syntax
> to be used in the same call, so in practice this confusion does not
> If the syntax "**expression" appears in the function call,
> "expression" must evaluate to a (subclass of) dictionary, the contents
> of which are treated as additional keyword arguments. In the case of a
> keyword appearing in both "expression" and as an explicit keyword
> argument, a TypeError exception is raised.
More information about the Python-list