Check out these lesser-known Python features

  • Published
  • Posted in Tech News
  • 2 mins read

*args, **kwargs

Occasionally, you may notice that a function definition contains these two arguments, like def func(x, y, *args, **kwargs).

They’re both incredibly simple features and allow us to pass multiple values to a function, which will then be packed into a generator.

It has a similar outcome as if we passed a list/generator to a standard argument:

def func(values):
    for x in values:
        print(x, end=" ")func([1, 2, 3])

[Out]: '1 2 3 '

Now, let’s use *args — this will allow us to pass each value as a new argument, rather than containing them all within a list.

def func(*values):
    for x in values:
        print(x, end=" ")func(1, 2, 3)

[Out]: 1 2 3

Note that we didn’t need to type *args. Instead, we typed *values. The variable name we use is irrelevant. It is defined as an *args, thanks to the single asterisk *.

*args simply creates a tuple from the arguments we pass into a function.

**kwargs on the other hand, creates a dictionary. Hence the name, key-word arguments. We use it like so:

def func(**values):
    for x in values:
        print(f"{x}: {values[x]}")func(x=1, y=2, z=3)[Out]: x: 1
       y: 2
       z: 3

Again, we can call the variable whatever we want. In this case, we used **values. It is defined as a **kwargs by the use of a double asterisk **.

News Article Courtesy Of James Briggs »