*args and **kwargs
Functions that accept any arguments.
🎬 Video version coming soon — read it now
Sometimes a function should accept any number of arguments. *args and **kwargs make that possible, and you'll see them in almost every library and decorator.
*args: extra positional arguments
def total(*amounts):
print(type(amounts)) # <class 'tuple'>
return sum(amounts)
print(total(10, 20)) # 30
print(total(5, 15, 25, 55)) # 100The * gathers all the extra positional arguments into a tuple. The name args is just a convention.
**kwargs: extra keyword arguments
def make_profile(name, **details):
print(type(details)) # <class 'dict'>
profile = {"name": name}
profile.update(details)
return profile
print(make_profile("Kavya", city="Vizag", role="Analyst", cgpa=8.7))** gathers extra keyword arguments into a dictionary.
Order of parameters
def f(a, b=2, *args, key=None, **kwargs):
...Normal parameters, then defaults, then *args, then keyword-only parameters, then **kwargs. Anything after *args (like key) can only be passed by name.
Unpacking when calling
The same symbols work the other way: they spread a list or dict into arguments.
def area(width, height):
return width * height
dims = [4, 5]
print(area(*dims)) # area(4, 5)
opts = {"width": 3, "height": 7}
print(area(**opts)) # area(width=3, height=7)
merged = {**{"a": 1}, **{"b": 2}} # {'a': 1, 'b': 2}
first, *rest = [1, 2, 3, 4] # first=1, rest=[2, 3, 4]Passing arguments through
The most important real use: a function that wraps another and passes everything along unchanged.
def logged(func, *args, **kwargs):
print(f"Calling {func.__name__} with {args} {kwargs}")
return func(*args, **kwargs)
logged(area, 4, height=5)This is exactly how decorators work, coming up shortly.
Keyword-only parameters
def send(message, *, urgent=False):
...
send("Hi", urgent=True) # OK
send("Hi", True) # TypeErrorA bare * forces callers to name the arguments after it, which prevents confusing calls like send("Hi", True).
In one line
*args collects extra positional arguments into a tuple, kwargs collects keyword arguments into a dict, and the same symbols unpack when calling.**
Share with a friend