ស្វែងយល់អំពី​ *args និង **kwargs ដែលតែងតែប្រេីក្នុង Python

Kit Bunrong

Bunrong / July 22, 2022

2 min read

*args

So what does *args exactly do for us? *args it takes the positional parameters passed by the user to a function, and store them into a list called args

Let’s see the most important properties of this construct:

  • the name args is just a convention, you can call it however you want as long as you put a * before the name.
  • it only stores positional arguments, i.e. parameters which are passed without specifying the name.

if you don’t know the difference between positional and keyword arguments, consider this example: f(3, 4, x=5, y=6). Here is 3 and 4 are positional arguments, because we have not specified a name for them. 5 and 6 are keyword arguments, and in fact, we have specified their names (x and y)

So how will our function become if we use *args?

def sum_values_args(*args):
	s = 0
	for el in args:
		s += el
	return s

Now user can use it as if these were normal parameters of a function, and they will be automatically converted to a list:

sum_values_args(1,2,3)

**kwargs

**kwargs is keyword arguments that can take any number of keyword arguments (i.e. parameters which were specified together with their names) and then convert them to a dictionary, using the keywords as keys.

Example: if a user calls,

print_out(author="Me", time="9:00", date="today")

inside the function kwargs will be a dictionary containing:

print_out(author="Me", time="9:00", date="today")

So now we can create our generalized print_out function:

def print_out(**kwargs):
  for key in kwargs:
    print(key + ": " + kwargs[key])

Note that kwargs is just a convention, you can call it however you want as long as you add ** before the name.

The result of using our function will be:

>>> print_out(author="Me", time="9:00", date="today")
author: Me
time: 9:00
date: today
>> print_out(author="Someone", text="My example text")
author: Someone
text: My example text

Lastly, remember that you can always use both *args  and **kwargs  together. If you do, args  will be a list containing all the positional arguments, whereas kwargs  will contain the keyword arguments.