Topic 57 of 64
*args
Overview
*args captures any number of positional arguments into a tuple. It enables functions to accept variable numbers of inputs — used extensively in decorator patterns, math utilities, and flexible APIs.
Syntax
python
def add_all(*args: int) -> int:
return sum(args)
add_all(1, 2, 3) # 6
add_all(10, 20, 30, 40) # 100
# args is a tuple inside the function
def show(*args):
print(type(args)) # <class 'tuple'>
for item in args:
print(item)
# Spreading a list with *
nums = [1, 2, 3]
add_all(*nums) # same as add_all(1, 2, 3)Common Pitfalls
- *args must come after regular positional parameters and before **kwargs in the function signature.
- The name 'args' is a convention — *anything works, but *args is universally understood.
- Interview tip: *args in a function call (not definition) is the 'spread' or 'unpack' operator — it expands an iterable into positional arguments.
Real-World Example
A logging function that accepts variable message parts
example
python
import datetime
def log(*parts: str, level: str = "INFO") -> None:
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
message = " ".join(str(p) for p in parts)
print(f"[{timestamp}] [{level}] {message}")
log("Server started on port", 8080)
log("User", "alice@example.com", "logged in", level="DEBUG")
log("Critical failure", "DB unreachable", level="ERROR")