[Tutor] *args, **kwargs

Bruce Sass bsass@freenet.edmonton.ab.ca
Tue, 21 Aug 2001 01:57:20 -0600 (MDT)


On Tue, 21 Aug 2001, A wrote:

> Hi,
> I am a newbie with Python. Can you please let me know what is a
> difference between *args and  **kwargs and how I can use them?

Playing with the interpreter is the best way to get a feel for what
they do...

>>> def test(pos, *arg, **keyed):
...   print pos
...   print arg
...   print keyed
...
>>> test('positional', 'an argument', key='value')
positional
('an argument',)
{'key': 'value'}
>>> test(1, 2, 3, four=4, five=5)
1
(2, 3)
{'five': 5, 'four': 4}

...*<args label> collects non-positional arguments into a tuple named
<args label>, **<keys label> collects keyword arguments into a
dictionary named <keys label>.

Section 4.7 of the Tutorial gives a good introduction.


- Bruce