Python *args and **kwargs

Pybeginner
By -
0

 


Well, technically it's *any **anything, but the convention is *args and **kwargs.

Python *args

*args and **kwargs are often used in function definitions. Both allow you to pass a variable (or shall we say a number you can't plan for) number of arguments to a function.

*args is used to pass a keyword-free variable-length argument list to the function.


 

def test_args(p_arg, *args):

    print("first normal argument:", p_arg)

    for arg in args:

        print("another arg through *args :", arg)

 

test_args('John','Futi','Using','Python')

 


Output —---------------- ----

normal first argument: Joao

another arg through *args : I got

another arg through *args : Using

another arg through *args : Python


Python **kwargs

So we saw how *args is used to pass a list of variable-length arguments without keywords. **kwargs does this, but for named/keyworded arguments!


 

def test(**kwargs):

    if kwargs is not None:

        for key, value in kwargs.items():

            print("%s says %s" % (key, value))

 

test(Python="Good morning", John="hi")

 


Output —--------------------

Python says Good morning

John says hi


Passing arguments and kwargs in Python functions


Let's say you want to write a list and you want to pass the elements of the list to the function.


 

def test_function(p1, p2, p3):

    print(p1,p2,p3)

    return

 


You can't pass a list or tuple to this because the entire list or tuple will be passed as the first argument...

SO HOW DO YOU DO THAT?


 

def test_function(p1, p2, p3):

    print(p1,p2,p3)

    return

 

arguments = (1,2,3)

 

test_function(*arguments)

 


Output —--------------------

1 2 3


You can do the same thing with kwargs also


def test_function(p1, p2, p3):

    print(p1,p2,p3)

    return

 

kwargs = {"p1": 1, "p2": 2, "p3": 3}

 

test_function(*kwargs)

 


Output —--------------------

p1 p2 p3


Note that writing "p4":4 will throw an exception as p4 was not defined in the function prototype

Iterating over arguments passed by args in Python


# If the function is defined

def function_name(*args):

     # Then

     arguments = arguments

     # Will have the arguments returning a tuple of arguments

   

# If the function is defined

def function_name(**kwargs):

     # Then

     arguments = kwargs

     # Will have arguments to return a dictionary of arguments

   

# You can use them to iterate using loops for



Args, Kwarg, sorting formal arguments


# Sorting is done like this function_name

( *args,args, **kwargs)


Tags:

Post a Comment

0Comments

Post a Comment (0)