*args And **kwargs In Python

Discover the power of *args and **kwargs in Python for flexible argument handling. Learn to manage multiple inputs in functions with practical examples efficiently.

In Python, *args and **kwargs allow functions to accept a variable number of arguments. *args is used for positional arguments, passed as a tuple, while **kwargs handles keyword arguments, passed as a dictionary. This flexibility facilitates the creation of versatile functions that can adapt to a wide range of input parameters.

What Is Python *args?

Python *args is a mechanism in function definitions that allows you to pass a variable number of positional arguments. This feature makes your functions more flexible, enabling them to accept any number of arguments without specifying each one individually in the function definition.

You use *args in the parameter list of a function to denote that the function can accept any number of positional arguments beyond those already named. The arguments passed to the function are accessible as a tuple within the function body.

For example, consider a function designed to sum any number of numbers.

def sum_numbers(*args):
    return sum(args)

print(sum_numbers(1, 2, 3))
print(sum_numbers(1, 2, 3, 4, 5))

Output.

6
15

In this code, sum_numbers can take any number of arguments, thanks to *args, and calculates their sum. This showcases the versatility and power of args in making functions adaptable to a wide range of inputs.

What Is Python **kwargs?

Python **kwargs is a parameter that allows a function to accept an arbitrary number of keyword arguments. These arguments are passed into the function as a dictionary, enabling dynamically handling named arguments. kwargs stands for keyword arguments, making functions flexible in dealing with named parameters.

For example, consider a function that needs to handle different attributes of a profile.

def create_profile(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

create_profile(name="John Doe", age=30, profession="Developer")

Output.

name: John Doe
age: 30
profession: Developer

In this code, **kwargs collects any number of named arguments passed to create_profile and prints out each key-value pair. This feature is handy when the exact number of keyword arguments is still being determined or may vary.

Using Both *args And **kwargs In Python To Call A Function

Using both *args and **kwargs in Python to call a function enables passing a variable number of arguments to a function. *args allows for any number of positional arguments, while **kwargs supports any number of keyword arguments. This flexibility makes your functions adaptable to various input scenarios.

Consider a function that needs to handle multiple types of arguments dynamically. With *args and **kwargs, you can accommodate those requirements seamlessly. Here's an example.

def function_example(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

function_example(1, 2, 3, name='Alice', job='Engineer')

Output.

Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'job': 'Engineer'}

This approach ensures that your function can accept a flexible number of arguments, enhancing its usability across different contexts.

Using *args and **kwargs In Python To Set Values Of Object

Using *args and **kwargs in Python allows for flexible assignment of values to objects. These two mechanisms enable the passing of a variable number of arguments to a function, where *args is used for tuple unpacking, and **kwargs for dictionary unpacking. This flexibility is beneficial in object-oriented programming when initializing object attributes.

For instance, *args can be used to pass multiple values to set up various attributes of an object in a single go. Consider a class Book where we want to assign attributes dynamically.

class Book:
    def __init__(self, *args):
        self.title, self.author, self.year = args

book = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925)
print(book.title, book.author, book.year)

Output.

The Great Gatsby F. Scott Fitzgerald 1925

Similarly, **kwargs allows for keyword argument passing, offering a more readable way to initialize object attributes.

class Book:
    def __init__(self, **kwargs):
        self.title = kwargs.get('title')
        self.author = kwargs.get('author')
        self.year = kwargs.get('year')

book = Book(title="1984", author="George Orwell", year=1949)
print(book.title, book.author, book.year)

Output.

1984 George Orwell 1949

These approaches show how *args and **kwargs provide versatility in handling object attributes, making code more adaptable and readable.

You can also check these blogs:

  1. When To Use Yield Instead Of Return In Python