How to call a method with variing arguments

Greg Ewing greg at cosc.canterbury.ac.nz
Thu Jul 5 22:39:43 EDT 2001


Malcolm Tredinnick wrote:
> 
> On Mon, Jul 02, 2001 at 11:40:49PM -0700, Heiko wrote:
> >
> > If possible, it would be nice, if the sequence of the arguments
> > doesn´t matter, and the method realizes which argument is on which
> > position (but that is a "nice to have").
> 
> I don't really know what you mean here, since I don't know how the
> function is meant to know which argument belongs where.

Heiko, I think you want keyword arguments. Given

  def foo(a, b, c):
    ...

you can call it like this:

  foo(b = 1, a = 2, c = 3)

If you declare

  def foo(**kw):
    ...

you can call it with any number of keyword arguments,
and kw receives a dictionary where the keys are the keywords
you used and the values are the values you passed.

You can mix and match all of these, too:

  def foo(a, b, c, *args, **kw):
    ...

can be called with 3 or more arguments. The first 3
can be passed positionally or by keyword; args
receives a tuple of the remaining positional arguments;
and kw receives a dictionary of the remaining keyword
arguments.

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list