Python Args and Kwargs

Python args and kwargs Made Easy

*args and **kwargs may seem scary, but the truth is that they are not that difficult to grasp and have the power to grant your functions with lots of flexibility.

Read the article Python *args and **kwargs Made Easy for a more in deep introduction.

Args and Kwargs

*args and **kwargs allow you to pass an undefined number of arguments and keywords when calling a function.

# Define a function that accepts any number of positional and keyword arguments
def some_function(*args, **kwargs):
    pass

# 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(arg, key1=arg1)

# Or call with no arguments at all
some_function()

Python conventions

The words *args and **kwargs are conventions. They are not imposed by the interpreter, but considered good practice by the Python community.

args

You can access the arguments through the args variable:

# *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 args tuple
some_function('arg1', 'arg2', 'arg3')
Arguments passed: ('arg1', 'arg2', 'arg3') as <class 'tuple'>
Quiz

Sign in to answer this quiz and track your learning progress

What data type does *args collect arguments into?
A. A list
B. A tuple
C. A dictionary
D. A set

kwargs

Keywords are accessed through the kwargs variable:

# **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 kwargs dict
some_function(key1='arg1', key2='arg2')
keywords: {'key1': 'arg1', 'key2': 'arg2'} as <class 'dict'>
Quiz

Sign in to answer this quiz and track your learning progress

What data type does **kwargs collect arguments into?
A. A list
B. A tuple
C. A dictionary
D. A set