DEV Community

Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on

1 1 1 1 1

Understanding '*args' and '**kwargs' in Python

πŸ”Ή Understanding *args and `kwargs` in Python**

In Python, *args and **kwargs are used to pass a variable number of arguments to a function.


READ Complete Article on this

πŸ”Ή What is *args?

  • *args allows a function to accept any number of positional arguments.
  • These arguments are collected as a tuple.

Example: Using *args

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

print(add_numbers(1, 2, 3))         # Output: 6
print(add_numbers(10, 20, 30, 40))  # Output: 100
print(add_numbers())                # Output: 0 (No arguments)
Enter fullscreen mode Exit fullscreen mode

How It Works?

  • *args collects 1, 2, 3 as a tuple β†’ (1, 2, 3)
  • The function sums all numbers and returns the result.

πŸ”Ή What is `kwargs`?**

  • **kwargs allows a function to accept any number of keyword arguments.
  • These arguments are collected as a dictionary.

Example: Using `kwargs`**

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

print_info(name="Alice", age=25, city="New York")
Enter fullscreen mode Exit fullscreen mode

Output:

name: Alice
age: 25
city: New York
Enter fullscreen mode Exit fullscreen mode

How It Works?

  • **kwargs collects name="Alice", age=25, city="New York" as a dictionary:
  {'name': 'Alice', 'age': 25, 'city': 'New York'}
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Using *args and `kwargs` Together**

You can combine both in a function.

Example:

def user_info(user_id, *args, **kwargs):
    print(f"User ID: {user_id}")
    print("Additional Info:", args)
    print("Other Details:", kwargs)

user_info(101, "Developer", "Python", name="John", age=30)
Enter fullscreen mode Exit fullscreen mode

Output:

User ID: 101
Additional Info: ('Developer', 'Python')
Other Details: {'name': 'John', 'age': 30}
Enter fullscreen mode Exit fullscreen mode

How It Works?

  • 101 β†’ goes into user_id
  • "Developer", "Python" β†’ goes into *args as a tuple
  • name="John", age=30 β†’ goes into `kwargs`** as a dictionary

πŸ”Ή Example in Django View

In Django ViewSets, *args, **kwargs are often used to pass additional arguments.

Example in Django ViewSet

from rest_framework.viewsets import ViewSet
from rest_framework.response import Response

class MyViewSet(ViewSet):
    def list(self, request, *args, **kwargs):
        print("Args:", args)      # Tuple of extra positional arguments
        print("Kwargs:", kwargs)  # Dictionary of extra keyword arguments
        return Response({"message": "Success"})
Enter fullscreen mode Exit fullscreen mode

How It Works in Django?

  • *args captures extra positional arguments.
  • **kwargs captures additional keyword arguments (like pk in retrieve).

πŸ”Ή Summary Table

Concept Description Stored As Example Call Example Inside Function
*args Multiple positional arguments tuple func(1, 2, 3) (1, 2, 3)
**kwargs Multiple keyword arguments dict func(name="Alice", age=25) {'name': 'Alice', 'age': 25}

πŸš€ Best Practices

βœ” Use *args when you don’t know how many positional arguments will be passed.

βœ” Use **kwargs when you don’t know how many keyword arguments will be passed.

βœ” Use both when creating flexible Django views or utility functions.

πŸ”Ή Understanding *args and `kwargs` in Flask & FastAPI**

Both Flask and FastAPI allow you to use *args and **kwargs to handle dynamic arguments in request handling.


πŸ”Ή Example in Flask

Flask allows dynamic routes, and *args and **kwargs can help handle unknown parameters.

βœ… Example: Flask Route with *args and `kwargs`**

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/user/<int:user_id>', methods=['GET'])
def get_user(user_id, *args, **kwargs):
    extra_params = request.args  # Get query parameters
    return jsonify({
        "user_id": user_id,
        "args": args,
        "kwargs": kwargs,
        "query_params": extra_params.to_dict()  # Convert to dictionary
    })

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ How It Works?

  • The URL pattern /user/<int:user_id> captures user_id as a positional argument.
  • *args and **kwargs capture additional data (if provided).
  • request.args retrieves query parameters.

βœ… Testing in Postman

Request:

GET http://127.0.0.1:5000/user/123?name=Alice&age=30
Enter fullscreen mode Exit fullscreen mode

Response:

{
    "user_id": 123,
    "args": [],
    "kwargs": {},
    "query_params": {
        "name": "Alice",
        "age": "30"
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Example in FastAPI

FastAPI uses *args and **kwargs in path operations and dependency injection.

βœ… Example: FastAPI with *args and `kwargs`**

from fastapi import FastAPI, Query
from typing import Dict

app = FastAPI()

@app.get("/items/{item_id}")
async def get_item(item_id: int, *args, **kwargs):
    return {
        "item_id": item_id,
        "args": args,
        "kwargs": kwargs
    }

@app.get("/query/")
async def query_example(name: str = Query(None), age: int = Query(None), **kwargs: Dict):
    return {
        "name": name,
        "age": age,
        "kwargs": kwargs
    }
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ How It Works?

  1. *args and **kwargs capture additional parameters that may be sent in the request.
  2. Query(None) allows extracting query parameters dynamically.
  3. `kwargs: Dict`** allows capturing additional keyword parameters.

βœ… Testing in Postman

Request:

GET http://127.0.0.1:8000/query/?name=Alice&age=30&city=NewYork
Enter fullscreen mode Exit fullscreen mode

Response:

{
    "name": "Alice",
    "age": 30,
    "kwargs": {
        "city": "NewYork"
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Summary of *args and `kwargs` in Flask & FastAPI**

Framework Use Case Example Call Result
Flask Capture extra route parameters and query params /user/123?name=Alice&age=30 Returns user_id, args, kwargs, and query_params
FastAPI Handle query parameters dynamically /query/?name=Alice&age=30&city=NewYork Captures name, age, and additional kwargs

πŸš€ Best Practices

βœ” Use *args for positional arguments (though rarely needed in APIs).

βœ” Use `kwargs to capture additional query params dynamically**.
βœ” **In Flask, use
request.args.to_dict()** to handle query parameters.
βœ” **In FastAPI, use
Query() and kwargs: Dict` for flexibility.

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong Β· web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌢️πŸ”₯

Top comments (0)

πŸ‘‹ Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay