π args & kwargs
Good to know
β args* collects any number of positional arguments into a tuple. β kwargs collects any number of named arguments into a dictionary. β Both are useful when you donβt know how many values a function will receive.
Using args (Positional Arguments)
args collects extra values into a tuple.
def add(*args):
print(args) # ('a', 'b', 'c')
return sum(args)
add(1, 2, 3)
# β 6Looping Through args
Useful for dynamic aggregations.
def print_all(*args):
for item in args:
print(item)
print_all("Jim", "Tom", 42)Using kwargs (Keyword Arguments)
kwargs collects named arguments into a dictionary.
def show_info(**kwargs):
print(kwargs) # {'name': 'Alain', 'age': 33}
show_info(name="Alain", age=33)Looping Through kwargs
Get both the key and the value.
def show_info(**kwargs):
for key, value in kwargs.items():
print(key, value)
show_info(first="Sir", middle="Alain", last="Haldi")Combining args and kwargs
Order matters: *args always comes before **kwargs.
def demo(a, b, *args, **kwargs):
print(a, b)
print(args) # extra positional values
print(kwargs) # extra named values
demo(1, 2, 3, 4, x=10, y=20)Passing a List or Dict Into a Function
You can unpack values when calling a function.
Unpack list β *args
def total(a, b, c):
return a + b + c
values = [1, 2, 3]
print(total(*values)) # same as total(1, 2, 3)Unpack dict β **kwargs
def greet(name, title):
print(title, name)
person = {"name": "Alain", "title": "Mr."}
greet(**person) # same as greet(name="Alain", title="Mr.")Real-World Example: Flexible Logging Function
def log(message, **data):
print(message)
for key, value in data.items():
print(f" - {key}: {value}")
log("User login", user="Alain", ip="127.0.0.1", success=True)