472,139 Members | 1,371 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,139 software developers and data experts.

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

On Fri, Oct 31, 2008 at 8:49 AM, mark floyd <em******@gmail.comwrote:
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"
Oct 30 '08 #1
0 2142

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Andrew Dalke | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.