🕯️ Magic Note
The name args is a convention, not a rule. The star is what matters. You can name it words, items, or *anything. Python collects all unmatched positional arguments into a tuple with that name. If no extra arguments are passed, the tuple is empty.
- The star parameter must come after all normal parameters
- It collects only positional arguments, not keyword arguments
- The tuple can be empty if no arguments are passed
- Use **kwargs (double star) for keyword arguments
| Function Call | Content of *words |
|---|---|
| spell() | () |
| spell(“magic”) | (“magic”,) |
| spell(“a”, “b”, “c”) | (“a”, “b”, “c”) |
| spell(1, 2, 3, 4, 5) | (1, 2, 3, 4, 5) |
Python
# Basic *args usage
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3, 4))
# Output: 10
print(sum_all(5, 10))
# Output: 15
Python
# Combining normal parameters with *args
def introduce(greeting, *names):
for name in names:
print(f”{greeting}, {name}”)
introduce(“Hello”, “Ali”, “Sara”, “Feloriya”)
# Output: Hello, Ali
# Output: Hello, Sara
# Output: Hello, Feloriya
Python
# Using *args in a decorator
def log_call(func):
def wrapper(*args, **kwargs):
print(f”Called with {args} and {kwargs}”)
return func(*args, **kwargs)
return wrapper
@log_call
def add(x, y):
return x + y
add(3, 5)
# Output: Called with (3, 5) and {}
- Placing *args before normal parameters, causing the normal parameters to never receive values
- Forgetting that *args collects only positional arguments, not keyword arguments like spell(a=1)
- Trying to name the star parameter *self inside class methods, which conflicts with instance reference conventions
⚡ Whisper
One star opens infinite doors. The function no longer counts your offerings. It accepts all with silence. One value. Many values. None at all. The star embraces every path.