Passing parameters to functions

Robert Brewer fumanchu at amor.org
Tue May 25 22:56:34 EDT 2004


Thomas Philips wrote:
> Thanks for the explanation. A follow up question: Suppose I want to
> pass AT LEAST 2 positional arguments and AT LEAST 2 keyword arguments
> into a function, Then I think I would logically define the function as
> follows
> 
> def f(parg1, parg2, karg1="yes", karg2="no", *pargs, **kargs):
>     print parg1, parg2, pargs, karg1, karg2, kargs
> 
> and I expect that 
> f(1, 2, 3, 4, 5, karg1="maybe", karg2="maybe not", m="yes", n="no")
> 
> will return
> 1 2 (3, 4, 5) "maybe" "maybe not" {'m': "yes", 'n': "no"}
> 
> But instead I get an error: 
> f() got multiple values for keyword argument 'karg1'

Arguments get bound in order. So in your example:

The name "parg1" gets bound to the object whose value is 1, then
the name "parg2" gets bound to the object whose value is 2, then
the name "karg1" gets bound to the object whose value is 3, then
the name "karg2" gets bound to the object whose value is 4.

...the next argument passed in is a keyword arg; unfortunately, you've
already bound the name "karg1" to the value 3. Hence the exception.

> For the reasons you outlined earlier, the alternate form 
> f(1, 2,karg1="maybe", karg2="maybe not", 3, 4, 5, m="yes", n="no")
> generates a syntax error. 

I don't think you can pass keyword args before non-keyword args like
that.

> How can I pass all these arguments into the function cleanly?

Given:
   f(1, 2, 3, 4, 5, karg1="maybe", karg2="maybe not", m="yes", n="no")

...it looks like you're trying to pass a variable number of integers,
plus some named values. I'd probably stop trying to shoehorn the
integers into positional arguments, and use a tuple instead:

>>> def f(integers, karg1="yes", karg2="no", **kargs):
... 	print integers, karg1, karg2, kargs
... 	
>>> f((1,2,3,4,5))
(1, 2, 3, 4, 5) yes no {}
>>> f((1,2,3,4,5), "perhaps")
(1, 2, 3, 4, 5) perhaps no {}
>>> f((1,2,3,4,5), "perhaps", m="yes", n="no")
(1, 2, 3, 4, 5) perhaps no {'m': 'yes', 'n': 'no'}


Hope that helps,

Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list