Functions, *args, **kwargs and closures
Two skills that every decorator, callback and config helper is built on: passing values into a function in every way Python allows, and functions that remember values after the code that made them has finished. Each one is introduced on its own first, with a tiny example.
Foundations · Python for data engineers · Bronze · Everyday idioms, lesson 3 of 3
On this page
Read first: Mutability, copies and default arguments (skip if you know it)
In plain words first
At a café you can order "coffee, large, oat milk" in the usual order, or name each part in any order: "milk: oat, size: large". Function calls work the same way, by position or by name.
Passing values: by position or by name
You can pass a value by its position (first value to the first parameter) or by its name. By name, the order no longer matters, and the call explains itself:
def fare(km, rate): return km * rate print(fare(3, 8)) # by position: km=3, rate=8 print(fare(rate=8, km=3)) # by name, in any order
Output from a real run
24 24
*args: any number of values
A parameter with one star in front collects all the extra values into a tupletuple: An ordered, immutable sequence like ("Pune", 2026). Because it cannot change, it can be a dict key; use it for small fixed records. Learn more →. Use it when callers may pass two values or twenty:
def total(*amounts): print("amounts is", amounts) return sum(amounts) print(total(120, 80)) print(total(50, 25, 10))
Output from a real run
amounts is (120, 80) 200 amounts is (50, 25, 10) 85
**kwargs: any number of named values
Two stars collect all the extra named values into a dict, name to value:
def tag(order_id, **details): print(order_id, "details is", details) tag("o1", rain=True, floor=3) tag("o2")
Output from a real run
o1 details is {'rain': True, 'floor': 3}
o2 details is {}The names args and kwargs are only a habit; the stars do the work. You will see *args, **kwargs together in every decoratordecorator: A function that takes a function and returns a new one with extra behaviour around it, such as logging, retries or timing. Applied with @name above a def. Learn more →, because together they accept anything.
Every kind of parameter at once
The fee function below uses four kinds at once: a normal parameter (base), *extras for any extra values, surge, which must be passed by name, and **notes for any extra named values. The table shows where each value of the first call lands.
In fee(20, 5, 3, surge=1.5, rain=True) | Lands in | Because |
|---|---|---|
20 | base = 20 | The first value fills the first normal parameter |
5, 3 | extras = (5, 3) | *extras collects every extra value without a name, as a tuple |
surge=1.5 | surge = 1.5 | It is passed by name and matches a parameter |
rain=True | notes = {'rain': True} | **notes collects every named value that matches no parameter, as a dict |
def fee(base, *extras, surge=1.0, **notes): return round((base + sum(extras)) * surge, 2), notes # base=20, extras=(5, 3), surge=1.5, notes={"rain": True} total, notes = fee(20, 5, 3, surge=1.5, rain=True) print("total:", total, "| notes:", notes) # The same call style, unpacked from a list and a dict: charges = [10, 2] # *charges -> fee(10, 2, ...) options = {"surge": 2} # **options -> fee(..., surge=2) total, notes = fee(*charges, **options) print("total:", total, "| notes:", notes)
Output from a real run
total: 42.0 | notes: {'rain': True}
total: 24 | notes: {}The second call goes the other way: in a call, *charges spreads a list into separate values and **options a dict into named values. Anything after *extras (or a bare *) is keyword-only: callers must write surge=1.5, which keeps calls readable and lets you add parameters later safely.
Closures: functions with a backpack
A function defined inside another one can use the outer function's variables, and, surprisingly, keeps them after the outer function has finished, as if it packed them into a backpack. That function plus its backpack is a closure.
Step 1 · call the outer
make_fee(20) starts running, with its own variable base = 20.The command
city_fee = make_fee(20)
Step 2 · make the inner
def fee(km) creates a function that uses base. Python notices and packs base into its backpack.The command
def fee(km): return base + 8 * km
Step 3 · return it
make_fee returns fee and finishes. Normally its variables would now be thrown away, but base lives on in the backpack.The command
return feeStep 4 · use it later
city_fee(3) runs fee, which takes base = 20 out of its backpack: 20 + 8 × 3 = 44.The command
city_fee(3) # 44
Each call of the outer function creates new variables, so each inner function remembers its own.
def make_fee(base): def fee(km): return base + 8 * km return fee city_fee = make_fee(20) airport_fee = make_fee(60) print("city, 3 km:", city_fee(3)) print("airport, 3 km:", airport_fee(3))
Output from a real run
city, 3 km: 44 airport, 3 km: 84
airport_fee came from a separate call, so it carries its own base of 60.
Changing a remembered variable: nonlocal
Reading an outer variable just works, but assigning to it makes Python treat the name as a brand-new variable inside the inner function. So total += amount tries to read a local total that does not exist yet:
def make_tally(): total = 0 def add(amount): total += amount # Python thinks total is a new, empty variable return total return add add = make_tally() try: add(40) except UnboundLocalError: print("UnboundLocalError: total has no value inside add")
Output from a real run
UnboundLocalError: total has no value inside add
nonlocal total fixes it. It tells Python "this name belongs to the function around me; change that one":
def make_tally(): total = 0 def add(amount): nonlocal total total += amount return total return add kiran = make_tally() arun = make_tally() # a separate total kiran(40) print("kiran:", kiran(25)) # 40 + 25 print("arun:", arun(10))
Output from a real run
kiran: 65 arun: 10
Late binding in loops
A function made inside a loop does not copy the loop variable. It remembers the variable's name and looks up its value only when it is called. By then the loop has finished, so every function made in the loop sees the last value.
Below, the loop builds two fare calculators: ₹5 per km for an auto and ₹8 per km for a cab. Both are called after the loop ends, when rate is already 8.
calculators = [] for rate in (5, 8): # 5 for an auto, 8 for a cab calculators.append(lambda km: km * rate) # The loop has ended, so rate is now 8 for both auto, cab = calculators print("auto:", auto(10), "cab:", cab(10))
Output from a real run
auto: 80 cab: 80
The auto should cost 50, not 80. The fix is a default argument, rate=rate. A default value is worked out once, when the function is made, so each calculator keeps its own copy of rate: 5 for the first, 8 for the second.
calculators = [] for rate in (5, 8): calculators.append(lambda km, rate=rate: km * rate) auto, cab = calculators print("auto:", auto(10), "cab:", cab(10))
Output from a real run
auto: 50 cab: 80
A second fix uses the closure pattern from the start of this lesson. Move the calculator into its own function, make_calculator(rate), and call it once per rate. Each call gets its own rate that later loop steps cannot change, just as make_fee(20) and make_fee(60) each kept their own base.
def make_calculator(rate): def calculate(km): return km * rate return calculate calculators = [] for rate in (5, 8): calculators.append(make_calculator(rate)) # a new call, a new rate each time auto, cab = calculators print("auto:", auto(10), "cab:", cab(10))
Output from a real run
auto: 50 cab: 80
lambda: a function written with def inside the loop has the same problem, and the same two fixes work.When to reach for this
- Keyword-only settings: put options after
*(def load(path, *, retries=3)) so every call saysretries=5, not a bare 5. - Passing arguments through:
*args, **kwargsin a wrapper hands them on unchanged, as decorators do. - Configure once, call many times: a closure like
make_fee(20)instead of passing the same base on every call. - Small private state: a counter in a closure with
nonlocal; for more state, a class.
Common mistakes
- Assigning to an outer variable without nonlocal — UnboundLocalError. Declare it nonlocal.
- Using a global for per-object state — Every caller shares it. Use a closure or a class.
- Creating functions in a loop that use the loop variable — They all see the last value. Copy it with a default argument (rate=rate), or build each one in its own function call.
Key takeaways
- Pass values by position or by name; parameters after * must be passed by name.
- *args collects extra values into a tuple, **kwargs extra named values into a dict; * and ** spread them out in calls.
- A closure is a function plus a backpack of outer variables; assign to them with nonlocal.
- Functions made in a loop all see the last loop value; copy it in with a default argument.
Interview prep
THE QUESTION
"What is a closure, and when have you used one?"
Avoid: "a closure is a lambda". Any nested function that uses outer variables is a closure; lambdas are just one syntax.
Follow-ups · answer out loud, then open
Follow-up"Why do functions created in a loop all use the last loop value?"
Scenario"Write a helper that hands out increasing batch ids for each pipeline run, without globals."
Trap"def f(*args) receives a list of the arguments."
Check yourself
4 questionsdef total(*amounts) is called as total(5, 7). What is amounts?
Show the answer
(5, 7). A single-star parameter collects the extra values into a tuple.
def f(a, *b, c): ... How must c be passed?
Show the answer
By keyword. Parameters after *b are keyword-only.
Inside an inner function, total += 1 without nonlocal raises...
Show the answer
UnboundLocalError. Assignment makes total local to the inner function.
[lambda: i for i in range(3)] — what do the three functions return?
Show the answer
2, 2, 2. They look i up when called, after the loop ended at 2.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Functions and laziness · 8 min readDecorators
What @ does, wrappers for any function, functools.wraps, and decorators with arguments.
Related lessons
Previous: Mutability, copies and default arguments
Primary sources: Defining functions · The nonlocal statement