A good example to explain *args and **kwargs in python
March 10th, 2009
I read this wonderful example here: http://www.megasolutions.net/python/-args-and—kwargs-78766.aspx
>>> def a(*stuff): print repr(stuff) >>> def b(**stuff): print repr(stuff) >>> def c(*args, **kwargs): print 'args', repr(args) print 'kwargs', repr(kwargs) >>> a(1,2,3) (1, 2, 3) >>> b(hello='world', lingo='python') {'hello': 'world', 'lingo': 'python'} >>> c(13,14,thenext=16,afterthat=17) args (13, 14) kwargs {'afterthat': 17, 'thenext': 16} >>> args = [1,2,3,4] >>> kwargs = {'no-way': 23, 'yet-anotherInvalid.name': 24} >>> c(*args, **kwargs) args (1, 2, 3, 4) kwargs {'no-way': 23, 'yet-anotherInvalid.name': 24}
Here is some simple explaination about *args and **kwargs
Basically ‘args’ is a tuple with all the positional arguments, kwargs is a dictionary with all the named arguments.
Likewise you can pass a tuple to a function like func(*tuple), or a dict like func(**dictionary) or both, where the zuple has to come first.
Recent Comments