Sahaj.blogs
18 Sept 2023 · StudyPhase 1 · Python

Python · Functions: *args, **kwargs and scope

Variable-length arguments with *args and **kwargs, keyword-only parameters, unpacking at the call site, and LEGB scope.

  • *args collects any extra positional arguments into a tuple.
  • **kwargs collects 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) and f(**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
3

#python#functions

Sources

  1. Arbitrary Argument Lists — Python Software Foundation
  2. Python Scopes and Namespaces — Python Software Foundation
  3. PEP 3102: Keyword-Only Arguments — Python Software Foundation