By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,766 Members | 1,435 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,766 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.