Python *args and **kwargs

(A new post, in the spirit of always be jabbing, always be firing, always be shipping. )

This post deals with Python *args and **kwargs. Here args and kwargs are just naming conventions, the grammar is actually * and ** .

*args

Define variable length of parameters for a function. In plain English, the number and type of parameters are not known beforehand.

Example:


def test_var_args(f_arg, *argv):
print("first normal arg: ", f_arg)
for arg in argv:
print("another arg through *argv :", arg)

test_var_args('Yasoob', 'python', 'eggs', 'test')

The output is


first normal arg: Yasoob
another arg through *argv : python
another arg through *argv : eggs
another arg through *argv : test


**kwargs

Similar to *args in that it enables variable length inputs. But different in that the inputs can be named.

Example:


def table_things(**kwargs):
for name, value in kwargs.items():
print( '{0} = {1}'.format(name, value))

table_things(apple = 'fruit', cabbage = 'vegetable')

The output is


apple = fruit
cabbage = vegetable

References:

https://stackoverflow.com/questions/3394835/args-and-kwargs

https://pythontips.com/author/yasoob008/

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *