Python · Functions: *args, **kwargs and scope
Variable-length arguments with *args and **kwargs, keyword-only parameters, unpacking at the call site, and LEGB scope.
*argscollects any extra positional arguments into a tuple.**kwargscollects any extra keyword arguments into a dict.- Parameters listed after a bare
*are keyword-only (PEP 3102). - At the call site it works the other way round:
f(*lst)andf(**d)unpack a list or dict into arguments.
Scope (LEGB). Python looks a name up in this order: Local, then Enclosing function, then Global (the module), then Built-in. To assign to a variable from an outer scope, you need nonlocal (enclosing function) or global (module level).
def describe(*args, sep=", ", **kwargs):
print("args:", args)
print("kwargs:", kwargs)
return sep.join(map(str, args))
print(describe(1, 2, 3, sep=" | ", unit="cm", rounded=True))
nums = [4, 5]
opts = {"sep": "+"}
print(describe(*nums, **opts))
def counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
c = counter()
print(c(), c(), c())
len = 5 # shadows the built-in in this module (don't do this!)
print(len)
del len
print(len("abc"))
Output:
args: (1, 2, 3)
kwargs: {'unit': 'cm', 'rounded': True}
1 | 2 | 3
args: (4, 5)
kwargs: {}
4+5
1 2 3
5
3Sources
- Arbitrary Argument Lists — Python Software Foundation
- Python Scopes and Namespaces — Python Software Foundation
- PEP 3102: Keyword-Only Arguments — Python Software Foundation