Sunday 4 July 2010

Passing arguments to Python functions

I found a good reference on how to pass arguments to Python functions using the star (or star-star) notation. You can find it here. Here goes a summary.

If you want to pass unnamed arguments, you can do as follows:

>>> a = (1,5)
>>> range( *a )
[1, 2, 3, 4]


If you want to pass named arguments, you need dictionaries:

>>> a = range( 1, 4 )
>>> b = range( 4, 8 )
>>> def concat( a, b ): return a + b
...
>>> concat( **dict( a = a, b = b ) )
[1, 2, 3, 4, 5, 6, 7]


You can mix named and unnamed arguments thus:

my_foo( *a, **b )

where a and b are a list and a dictionary. Caution needs to be taken to pass a single unnamed argument, though. Details can be found in the reference above.

No comments:

Post a Comment