Fri 18 Aug 2006
kwargs - Python keyword arguments
Posted by dkaz under Python, Programming
One of the more unique features of Python is the ability to collect all excess parameters passed to a method in a tuple (positional arguments) or a dictionary (keyword arguments).
This last method parameter often follows the “**kwargs” convention in the code I’ve run into.
When a final formal parameter of the form
**nameis present, it receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form*name(described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. (*namemust occur before**name.) For example, if we define a function like this:def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, '?' print "-- I'm sorry, we're all out of", kind for arg in arguments: print arg print '-'*40 keys = keywords.keys() keys.sort() for kw in keys: print kw, ':', keywords[kw]It could be called like this:
cheeseshop('Limburger', "It's very runny, sir.", "It's really very, VERY runny, sir.", client='John Cleese', shopkeeper='Michael Palin', sketch='Cheese Shop Sketch')and of course it would print:
– Do you have any Limburger ?
– I’m sorry, we’re all out of Limburger
It’s very runny, sir.
It’s really very, VERY runny, sir.
—————————————-
client : John Cleese
shopkeeper : Michael Palinsketch : Cheese Shop Sketch

August 30th, 2006 at 3:58 pm
I don’t care how f’ing runny it is, fetch it with all speed!