Python Advance Course

agrs and kwargs in python

*args and **kwargs in Python (Flexible Function Arguments)

Python provides special syntax to allow functions to accept variable numbers of arguments:

  • *args → variable positional arguments
  • **kwargs → variable keyword arguments

These are widely used in: - APIs - Decorators - Libraries - Frameworks (like Django, Flask)


1. *args (Variable Positional Arguments)

*args allows a function to accept any number of positional arguments.

Example:

def add(*args):
    print(args)

add(1, 2, 3, 4)

Output:

(1, 2, 3, 4)

Real World Example

A billing system where items are added dynamically:

def total_bill(*items):
    return sum(items)

print(total_bill(100, 200, 300))

Output:

600

How *args works (Graph)

function(*args)
      |
      +--> collects all positional values
      |
      +--> stores as tuple

Common Mistake

def test(args):
    print(args)

test(1, 2, 3)

Problem: - Only accepts one argument, not multiple

Correct:

def test(*args):

Homework 1

Create a function that prints all numbers passed using *args.

Solution:

def show_numbers(*args):
    for num in args:
        print(num)

show_numbers(10, 20, 30)

2. **kwargs (Variable Keyword Arguments)

**kwargs allows passing named arguments dynamically.

Example:

def show_info(**kwargs):
    print(kwargs)

show_info(name="John", age=25)

Output:

{'name': 'John', 'age': 25}

Real World Example

User profile system:

def profile(**details):
    for key, value in details.items():
        print(key, value)

profile(name="Alice", role="Admin", active=True)

Output:

name Alice
role Admin
active True

Graph (Flow)

function(**kwargs)
      |
      +--> collects named arguments
      |
      +--> stores as dictionary

Common Mistake

def test(kwargs):
    print(kwargs)

test(name="John")

Problem: - Not using **kwargs, so multiple keyword args fail

Correct:

def test(**kwargs):

Homework 2

Create a function that prints key-value pairs using **kwargs.

Solution:

def show_data(**kwargs):
    for k, v in kwargs.items():
        print(k, v)

show_data(city="Delhi", country="India")

3. Using *args and **kwargs Together

You can combine both in one function.

Example:

def demo(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

demo(1, 2, 3, name="John", age=30)

Output:

args: (1, 2, 3)
kwargs: {'name': 'John', 'age': 30}

Real World Example

Order system:

def order(*items, **details):
    print("Items:", items)
    print("Details:", details)

order("Pizza", "Burger", table=5, paid=True)

Argument Order Rule

Order Rule
1 normal arguments
2 *args
3 default arguments
4 **kwargs

Graph

function(a, b, *args, **kwargs)

Homework 3

Create a function that accepts: - any number of items - customer name and order ID

Solution:

def shop(*items, **info):
    print(items)
    print(info)

shop("apple", "banana", name="Ravi", order_id=101)

4. *args and **kwargs in Decorators

Decorators use *args and **kwargs to handle flexible functions.

Example:

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function")
        result = func(*args, **kwargs)
        print("After function")
        return result
    return wrapper

Decorator Usage

@decorator
def add(a, b):
    return a + b

print(add(5, 10))

Output:

Before function
After function
15

Real World Example

Logging system:

def logger(func):
    def wrapper(*args, **kwargs):
        print("Calling:", func.__name__)
        return func(*args, **kwargs)
    return wrapper

Graph (Decorator Flow)

function(a, b)
     |
     v
wrapper(*args, **kwargs)
     |
     v
original function

Common Mistake

def wrapper():
    return func()

Problem: - Cannot handle arguments

Correct:

def wrapper(*args, **kwargs):

Homework 4

Create a decorator that prints function name and arguments.

Solution:

def debug(func):
    def wrapper(*args, **kwargs):
        print("Function:", func.__name__)
        print("Args:", args)
        print("Kwargs:", kwargs)
        return func(*args, **kwargs)
    return wrapper

@debug
def multiply(a, b):
    return a * b

multiply(4, 5)

Summary Table

Concept Meaning
*args variable positional arguments (tuple)
**kwargs variable keyword arguments (dict)
combined flexible function design

Real World Mapping

Feature Example
*args shopping cart items
**kwargs user profile data
decorators logging/auth systems

Visual Summary

*args   → (1, 2, 3)
**kwargs → {'a':1, 'b':2}

Next Advanced Topics

  • Closures (deep dive)
  • Decorators chaining
  • Generators (yield)
  • Iterators protocol
  • Context managers (with statement)
  • functools module (partial, lru_cache)
  • Async programming (async/await) ```

Filters

No filters available for this view.

Reset All