farmdev

What does the def-star-variable (or def-asterisk-parameter) syntax do in Python?

Inspired by Titus' blog post about Python's elusive at sign I thought I'd drop a little google egg for anyone who is learning Python and hasn't read the manual cover to cover yet (like I did ... yeah, right).

If you see a def in python with asterisks (or stars), like so:

def foo(*args, **kw):
    pass

...what does this syntax do? It is buried in the Python tutorial here, under More On Defining Functions > Arbitrary Argument Lists which would only appear in a google search if you already knew what the syntax does! The first form means any arbitrary number of arguments to the function foo will be provided to you in a tuple named args. And the second form means any arbitrary number of keyword arguments will be available in the dict kw. For example:

>>> def checkout(*items, **coupons):
...     print items
...     print coupons
... 
>>> checkout('eggs', 'cheese', 'cereal', 
...          cereal='10% off', cheese='buy 1 get 1')
('eggs', 'cheese', 'cereal')
{'cheese': 'buy 1 get 1', 'cereal': '10% off'}
>>> 

The above section in the tutorial has the details on the order in which this is achieved.

DISCLAIMER: The author of this post does not condone lazily learning a programming language by trial and error, reading other peoples' code, or simply googling for an answer to something :)