Passing parameters to functions
Jeff Epler
jepler at unpythonic.net
Tue May 25 22:48:06 EDT 2004
If you want to have a varying number of positional arguments, and
require certain keyword arguments, I think you'll be forced to write it
in a clumsy way, similar to (untested):
def extract_args(funcname, mapping, *names):
for i in names:
try:
yield mapping[i]
del mapping[i]
except KeyError:
raise TypeError, (
"%s requires a keyword argument %s" %
(funcname, repr(i))))
def f(parg1, parg2, *pargs, **kargs):
karg1, karg2 = extract_args("f()", kargs, "karg1", "karg2")
print parg1, parg2, pargs, karg1, karg2, kargs
When you write code like
def f(a, b=1)
Python will accept any of these calls to f:
f(0)
f(1, 2)
f(3, b=4)
f(a=5, b=6)
and even
f(b=7, a=8)
.. the call that is relevant to your case is the second one. The
value in b can come from a positional argument or a keyword argument.
In your case, when you cakk 'f(1, 2, 3, karg=3)' karg gets two
values---one from the third positional argument, and one from the
keyword argument.
Jeff
More information about the Python-list
mailing list