Python Args and Kwargs

PythonBeginner
Practice Now

Introduction

In this lab, you will learn about *args and **kwargs in Python. These special syntaxes may seem intimidating at first, but they are straightforward to understand and provide a powerful way to make your functions more flexible. You will learn how to define functions that can accept a variable number of arguments, which is a common and useful feature in many Python programs and libraries.

Args and Kwargs

In this step, you will learn the basic syntax of *args and **kwargs. These are used in function definitions to allow passing an undefined number of arguments. *args is for non-keyword, positional arguments, while **kwargs is for keyword arguments.

Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.

First, let's see how to define a function that can accept any combination of arguments. In the left-hand file explorer, find the file main.py located in the ~/project directory and open it in the editor.

Add the following code to main.py:

## Define a function that accepts any number of positional and keyword arguments
def some_function(*args, **kwargs):
    print("This function can accept any arguments.")
    print(f"Received positional arguments: {args}")
    print(f"Received keyword arguments: {kwargs}")
    print("-" * 20)

## Call with any number of positional arguments
some_function('arg1', 'arg2', 'arg3')

## Call with any number of keyword arguments
some_function(key1='arg1', key2='arg2', key3='arg3')

## Call with both positional and keyword arguments
some_function('positional_arg', key1='keyword_arg')

## Or call with no arguments at all
some_function()

It's important to note that args and kwargs are just naming conventions. The single asterisk (*) and double asterisk (**) are the actual syntax that does the work. However, following the convention is considered good practice in the Python community.

Now, run the script by opening a terminal in the WebIDE and executing the following command:

python3 main.py

You should see the following output, demonstrating how the function handles different calls:

This function can accept any arguments.
Received positional arguments: ('arg1', 'arg2', 'arg3')
Received keyword arguments: {}
--------------------
This function can accept any arguments.
Received positional arguments: ()
Received keyword arguments: {'key1': 'arg1', 'key2': 'arg2', 'key3': 'arg3'}
--------------------
This function can accept any arguments.
Received positional arguments: ('positional_arg',)
Received keyword arguments: {'key1': 'keyword_arg'}
--------------------
This function can accept any arguments.
Received positional arguments: ()
Received keyword arguments: {}
--------------------

This shows that *args collects positional arguments into a tuple and **kwargs collects keyword arguments into a dictionary.

args

In this step, you will focus specifically on *args. This syntax allows a function to accept an arbitrary number of positional arguments. These arguments are collected into a tuple.

Clear the previous content from main.py and add the following code. This example defines a function that takes *args and prints the arguments it receives, along with their type.

## *args collects positional arguments into a tuple
def some_function(*args):
    print(f'Arguments passed: {args} as {type(args)}')

## Pass multiple arguments - they'll be collected into the args tuple
some_function('arg1', 'arg2', 'arg3')

In this code, *args in the function signature tells Python to gather all extra positional arguments passed to some_function and put them into a tuple named args.

Now, run the script from the terminal:

python3 main.py

The output will confirm that the arguments were passed as a tuple:

Arguments passed: ('arg1', 'arg2', 'arg3') as <class 'tuple'>

This demonstrates how *args provides a simple way to handle a variable number of inputs without having to define each one as a separate parameter.

kwargs

In this step, you will learn how to use **kwargs. This syntax is used to collect an arbitrary number of keyword arguments into a dictionary. This is useful when you want to handle named arguments that you haven't defined in advance.

Clear the content of main.py and add the following code. This example defines a function that accepts **kwargs and prints the collected keyword arguments and their type.

## **kwargs collects keyword arguments into a dictionary
def some_function(**kwargs):
    print(f'keywords: {kwargs} as {type(kwargs)}')

## Pass keyword arguments - they'll be collected into the kwargs dict
some_function(key1='arg1', key2='arg2')

Here, **kwargs in the function signature tells Python to collect all keyword arguments passed to some_function into a dictionary named kwargs. The keys of the dictionary are the argument names, and the values are the argument values.

Run the script from the terminal:

python3 main.py

The output will show that the keyword arguments have been collected into a dictionary:

keywords: {'key1': 'arg1', 'key2': 'arg2'} as <class 'dict'>

This feature is widely used in Python for functions that need to pass options or configurations, allowing for clean and readable function calls.

Summary

In this lab, you have learned how to use *args and **kwargs in Python to create more flexible functions.

You learned that:

  • *args collects a variable number of positional arguments into a tuple.
  • **kwargs collects a variable number of keyword arguments into a dictionary.
  • args and kwargs are conventional names, but the * and ** syntax is what enables this functionality.

Mastering *args and **kwargs is a key step in writing more advanced and reusable Python code. You can now create functions that are more adaptable to different kinds of input.