Published: Oct. 15, 2019 by lukemakin |  estimated reading time: 8 minutes
Before we begin, there's someting you need to know - args & kwargs aren't difficult... they just look as they are. So if your face expression resembles the one in the picture above - we are going to change it to a smile after finishing reading this article. Let's begin with an simple example to see what actually is going on with those two:

def some_function(*args, **kwargs):
print('args', type(args), args)
print('kwargs', type(kwargs), kwargs)

some_function(1,2,3,"supersonic", 'gameboy', 7, 'alfa', team="Borussia Dortmund", movie="Interstellar")

'''
Output:
args <class 'tuple'> (1, 2, 3, 'supersonic', 'gameboy', 7, 'alfa')
kwargs <class 'dict'> {'team': 'Borussia Dortmund', 'movie': 'Interstellar'}
'''

The first remark is that with the use of args & kwargs we can pass undefined amout of arguments and keyword arguments when calling a function. The second one is that the function returns arguments as a tuple and keyword arguments as a dictionary. The third one is related to the difference between these two - arguments are single postional arguments (i.e. 1,2..'supersonic' etc.), passed in first, while keyword arguments (i.e. team="Borussia Dortmund") have assigned keywords and come after positional arguments. Finally the fourth one explains the "*" and "**" - their just unpacking operators to upack iterable objects. In our case "*" will be used for the tuples (args) "**" for the dictionaries (kwargs).

Let's practice, starting with the arguments! Let's return the first passed in argument:

def first_arg(*args):
return args[0]

first = first_arg(1,2,3,4,7,8,9, 'Jack')
print(first)

'''
output:
1
'''

We are dealing with a touple so arg[] is a way to access our arguments passed in to the function. No let's sum the arguments:


def sum_int(*args):
sum = 0
for num in args:
if isinstance(num, int):
num = num
else:
num = 0
sum += num
return sum

total = sum_int(1,2,3,4,7,8,9, 'Jack')
print(total)

'''
output:
34
'''


If for some reason we would like to get a list (and here let's remember that tuples are immutable while lists are mutable) in reveresed order, we could write something like this:


def reverse_list(*args, **kwargs):
arg_list = [arg for arg in args][::-1]
return arg_list

r_list = reverse_list(1,2,3,4,7,8,9, 'Jack')
print(r_list)

'''
output:
['Jack', 9, 8, 7, 4, 3, 2, 1]
'''

Now few excersises with kwargs. Let's get them first!


def what_to_buy(**kwargs):
product = kwargs.get('chips', None)
return product

chips = what_to_buy(chips="Lays")
print(chips)

'''
output:
Lays
'''

And let's have a look how to loop through keyword arguments:


def best_players_on_their_positions(**kwargs):
for position in kwargs.values():
print(position)

my_best = best_players_on_their_positions(goalkeeper="G. Buffon", defender="S. Ramos", midlefielder="L. Modric", striker="R. Lewandowski")
print(my_best)

'''
output:
G. Buffon
S. Ramows
L. Modric
R. Lewandowski
'''

If we would like to get the positions only we would write kwargs.keys() and if we would like to get both position with the player - we would use kwargs.items(). Let's look another example with if/elif/else statements:


def what_to_buy(item, *args, **kwargs):
if 'store' in kwargs:
return "Buy {} in {}".format(item, kwargs['store'])
elif 'order' in kwargs:
return "You already ordered this {}".format(item)
else:
return "Make {} yourself insted of buying".format(item)

inst = what_to_buy("Laser", store="BestBuy")
print(inst)

'''
output:
Buy Laser in BestBuy
'''


If the concept of args & kwargs is still scary for you, consider changing the names to something nicer <just joking> but ... it's not obligatory to use args & kwargs - it's a good practice tough. If for some reason you decide to use different naming, remeber to put "*" and "**" at the front. Hopefully this was helpful, if not let me know in the comments.

 
Extras
To view additional content login or create a free account
Categories:
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com