Codectionary / Developer documentation / Python

*args and **kwargs

*args and **kwargs let a function accept a variable number of arguments. *args collects any extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a dictionary. The names 'args' and 'kwargs' are just convention - what matters is the * and ** prefixes. This pattern is common in wrapper functions, decorators, and APIs that need to stay flexible about their inputs.

Syntax

def func(*args, **kwargs):

Examples

Using *args

Accepting any number of positional arguments.

def sum_all(*numbers):
    total = 0
    for n in numbers:
        total += n
    return total

print(sum_all(1, 2, 3))         # 6
print(sum_all(10, 20, 30, 40))  # 100
print(sum_all())                # 0

Using **kwargs

Accepting any number of named keyword arguments.

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

print_profile(name="John", age=21, course="Software Engineering")

Combining Both

A function that accepts regular parameters, extra positional args, and extra keyword args together.

def describe(title, *args, **kwargs):
    print(f"Title: {title}")
    print(f"Extra positional: {args}")
    print(f"Extra keyword: {kwargs}")

describe("Report", "Q1", "Q2", author="John", pages=12)
# Title: Report
# Extra positional: ('Q1', 'Q2')
# Extra keyword: {'author': 'John', 'pages': 12}

Unpacking When Calling

* and ** also work in reverse - spreading an existing list/dict into a function call.

def add(a, b, c):
    return a + b + c

values = [1, 2, 3]
print(add(*values))  # 6

info = {"a": 10, "b": 20, "c": 30}
print(add(**info))   # 60

Best practices

  • Use *args when the number of positional inputs varies, and **kwargs when you want named, optional configuration options
  • Place *args and **kwargs after any required named parameters in a function signature (def func(a, b, *args, **kwargs))
  • Use **kwargs sparingly in your own APIs - overly flexible signatures can make it unclear what arguments are actually expected
  • Combine *args/**kwargs with function wrappers or decorators when you need to pass arguments through to another function unchanged

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading