Python 2.5: wrong number of arguments given in TypeError for function argument aggregation (dictionary input vs the norm)

James Mills prologic at shortcircuit.net.au
Thu Oct 30 18:55:26 EDT 2008


On Fri, Oct 31, 2008 at 8:49 AM, mark floyd <emfloyd2 at gmail.com> wrote:
> I was doing some testing with the different ways to pass arguments into
> functions and ran into what looks like a bug.
>
> Given function,
>
> def foo(a,b,c):
>     print a
>     print b
>     print c
>
> # Call function with named parameter list, leaving 'b' out
> foo(a=1, c=3)
>
> Traceback (most recent call last):
>   File "aggregate.py", line 13, in <module>
>     foo(a=1, c=3)
> TypeError: foo() takes exactly 3 arguments (2 given)
>
> # Call function with dictionary for parameter list... leaving 'c' out of the
> dictionary
> yarg = {'a': 111,  'b': 222}
> foo(**yarg)
>
> Traceback (most recent call last):
>   File "aggregate.py", line 17, in <module>
>     foo(**yarg)
> TypeError: foo() takes exactly 3 non-keyword arguments (2 given)
>
>
> # Call function with dictionary for parameter list... leaving 'b' out of the
> dictionary
>
> yarg = {'a': 111,  'c': 333}
> foo(**yarg)
>
> Traceback (most recent call last):
>   File "aggregate.py", line 17, in <module>
>     foo(**yarg)
> TypeError: foo() takes exactly 3 non-keyword arguments (1 given)
>
> It seems like the interpreter craps out too early when you leave 'b' out of
> the input dictionary... and it reports the incorrect number of arguments
> given (I would expect to see '2 given')
>
> We've tested this locally using Python 2.5, Debian Etch 32-bit installation

Mark, this is correct behavior. You have
3 positional arguments in the function
definition. You _must_ aupply _all_ 3
of them. If you wish for b to be optional,
then you must give it a default value.

def foo(a, b=None, c=None):
   print a
   print b
   print c

Note, that c must also be a default argument
as you cannot have a non-default argument following
a default argument.

A more useful approach is this common pattern:

def foo(*args, **kwargs):
   ...

What you have discovered is not a bug :)

cheers
James

-- 
--
-- "Problems are solved by method"



More information about the Python-list mailing list