parameter passing question

Fredrik Lundh fredrik at pythonware.com
Tue Sep 21 09:36:30 CEST 2004


Micah wrote:

> Use the variable-arg techniques described in:
> http://docs.python.org/ref/function.html
>
> def foo(*args):
>    # Do something with arg[0], arg[1], ...
>
> def main():
>    f = foo
>    args = ["hello", "world"]
>    f(*args)
>
> ------
>
> Is there a way to do it if I am not the one to define f?  In other words, if
> I cannot declare f to be a variable-argument function, is there a way to do
> it?

just use the f(*args) syntax when calling the function.

there's no separate "variable argument function" type in Python; on a
conceptual level, arguments are always passed as a tuple/dictionary
pair (where the tuple holds positional arguments, and the dictionary
holds keyword arguments).

the "f(a, b)" and "f(*args)" call formats are just two different ways to
build the tuple, and "def g(x, y)" and "def g(*args)" are just two different
ways to unpack it.

you can mix the two formats (both in calls and in function definitions), and
you can also use keyword arguments in the call for positional arguments in
the function.  for details, see:

    http://docs.python.org/ref/calls.html

(you may have to read that page more than once, or easier, just rely on the
fact that all combinations work just as you would expect).

</F> 






More information about the Python-list mailing list