Functions: Advanced
At Stripe, the API counts money in the smallest currency unit, so 2500 means $25.00. A refund script that calls refund(charge, 25, 2500) leaves its reader guessing: was that a 25-cent refund with a $25 fee, or the reverse? Python will run that call either way. This lesson builds functions that refuse it by name and raise instead of guessing. Later sections split a long function into parts you can check one at a time, then add a cache for repeated lookups and a recursive walker for nested webhook payloads.
The first call returns 2475 and the second returns -2475. A reviewer reading net_refund(25, 2500) cannot tell which number is the fee, and Python raises nothing. The cure is to make the caller write the names.
Keyword-only: every parameter after *
A bare * in a signature closes the positional slots. Each parameter after it must be passed as name=value, and a positional value aimed at one of them raises TypeError before the body runs.
Named arguments may arrive in any order because Python matches them by name. The rule mirrors *args: a parameter written after *args can only be filled by keyword, since *args swallows every remaining positional value. A bare * keeps that rule and accepts no extra values. A keyword-only parameter with no default is still required, so net_refund(amount_cents=2500) fails with missing 1 required keyword-only argument: 'fee_cents'.
Positional-only: every parameter before /
A / works the other way. Parameters to its left can only be filled by position, so no call site ever writes their names. Because no caller depends on those names, you can rename the parameters later without breaking anything, and the name stays free inside **kwargs, which matters when callers pass arbitrary labels.
Without the /, the keyword event_id="legacy_42" would collide with the positional "evt_1", and Python would raise add_labels() got multiple values for argument 'event_id'. With it, the label lands in labels beside region.
All 3 zones in a single signature
| Where the parameter sits | How the caller passes it | When to choose it |
|---|---|---|
| Before `/` | By position only | The name is internal and may change |
| Between `/` and `*` | By position or by name | Ordinary parameters with no special risk |
| After `*` | By name only | Values a reader could swap or misread |
The first 2 calls differ only in how amount_cents arrives, and the middle zone accepts it either way. Naming account_id breaks the / rule. Passing "usd" as a third positional value breaks the * rule: the signature has 2 positional slots, and Python reports 3 values for them.
Which call to export_table runs without raising TypeError?
name=value: export(rows, compress=True) says what export(rows, True) hides.A function makes a promise through its return value: parse_cents promises a whole number of cents. When a row holds "n/a", the function can't keep that promise, and it has 2 choices. It can return a stand-in such as -1 or None and hope every caller checks for it, or it can raise an exception and return nothing at all.
What a quiet failure costs
The readable rows add up to 2350 cents, but the -1 blended into the sum: the report is off by 1 cent, the "n/a" row vanished, and no line of output says anything went wrong. Returning None fails in a different place. The += line raises TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType', which points at the loop instead of the bad row, and every caller has to remember an is None check to avoid it.
A raise stops the function and travels up
raise ValueError("message") creates an exception object and throws it. The function stops on that line and returns nothing, and the exception goes to whoever called it. If that caller wrapped the call in a matching try/except, the except branch runs. If not, the exception climbs to the caller's caller, and on up, until something catches it or the program ends with a traceback.
int("n/a") raises its own ValueError, and parse_cents lets it pass through because it has nothing to add. A negative amount converts without complaint, so the rule against it has to come from the function itself, which raises. The loop decides what a bad row means for this job; here it reports the row and moves on.
def parse_cents(raw):cents = int(raw)if cents < 0:raise ValueError("amount cannot be negative")return centsdef load_batch(rows):good = 0rejected = 0for raw in rows:try:good += parse_cents(raw)except ValueError:rejected += 1return good, rejectedprint(load_batch(["1200", "-350", "n/a", "800"]))
Each rejected row leaves parse_cents at the line that fails, and the except branch in load_batch counts it
load_batch returns (2000, 2): 2000 cents from the 2 clean rows and a reject count the job can log or alert on. A wrong number never passes for a right one anywhere in the run.
What does this program print?
Choosing the exception type
| Situation | Raise | Example message |
|---|---|---|
| Right type, unacceptable value | `ValueError` | amount cannot be negative |
| Argument of the wrong type | `TypeError` | rows must be a list |
| Lookup key is missing | `KeyError` | no rate for gbp |
| A rule specific to your data | a subclass you define | refund exceeds original charge |
Callers catch by type, so the type is part of the function's interface. A custom exception is a class that names an existing exception in parentheses, which makes it a kind of that exception. After class RefundTooLarge(ValueError): pass, an except ValueError still catches it, and a caller who cares about this case alone can write except RefundTooLarge. The message names the rule that broke, for whoever reads the log.
- Raise as soon as the function knows it can't return a correct value
- Pick the type a caller would catch: ValueError, TypeError, KeyError or a subclass
- Write a message that names the rule the input broke
- Catch where someone can decide between skipping or quarantining the row and stopping the job
- Signal failure by returning -1 or 0, or by returning an empty string
- Catch an error inside a helper only to return None
- Wrap a call in except Exception and carry on without a record
- Use the same exception type for every failure in a module
Cut along the jobs
The coordinator has a single reject path where it had 3: any helper that raises ValueError sends the row to the same except. It returns (2096, 2), a pair other code can use. The 1296 inside that total is 1200 euro cents at 1.08 dollars per euro, rounded down by //.
Each row passes through 2 helpers in turn, and a ValueError from either becomes a reject in the coordinator's count
Each helper gets its own check
- Checking the conversion means building a batch and reading printed text
- Separate reject paths in 3 places, each with its own continue
- Prints the totals, so no other code can use them
- A new rule means editing the middle of the loop
- Each rule is checked by a line with values typed in place
- A single reject path: any ValueError from any helper
- Returns (total, rejected) for other code to use
- A new rule is a new raise in the helper that owns it
Where helpers go wrong
The program prints 450 and then a second line. What's the second line, and why?
to_usd_cents, read_amount, is_settled. A name like handle_row or step2 means its job was never pinned down, and the next change will pile more into it.In a batch, the same calls repeat with the same arguments: the rate for "eur" on every euro payment, the region for store 118 on every sale from that store. When a function's result depends only on its arguments, the first answer stays the answer, and computing it again is wasted work. Memoization stores each answer in a dict keyed by the arguments and returns the stored value on every later call.
The pattern takes 3 lines inside the function. If the key is missing from the cache, compute the value and store it; either way, return what the cache holds. In the program below, slow_rate stands in for an expensive lookup and counts how often it runs.
calls = 0def slow_rate(currency):global callscalls += 1table = {"eur": 108, "gbp": 127, "usd": 100}return table[currency]rate_cache = {}def cached_rate(currency):if currency not in rate_cache:rate_cache[currency] = slow_rate(currency)return rate_cache[currency]events = ["eur", "usd", "eur", "eur", "gbp", "usd", "eur", "usd"]for currency in events:cached_rate(currency)print("slow lookups:", calls)print("cache:", rate_cache)
Across 8 events with 3 distinct currencies, slow_rate runs once per currency and the dict answers every repeat
slow_rate ran 3 times for 8 events, once per distinct currency. The cache lives at module level, outside both functions, so it outlasts every call. cached_rate changes the dict's contents without rebinding the name rate_cache, so it needs no global statement; slow_rate needs one because calls += 1 rebinds calls.
The key must hold every input
A cache is correct only when its key captures everything the result depends on. If a rate depends on the currency and the day, a cache keyed by currency alone hands back day 1's rate for every later day. A tuple of the arguments covers both, and tuples work as dict keys because they can't change after they're created. A list can't be a key: cache[["eur", 2]] raises TypeError: unhashable type: 'list'.
rate_bad("eur", 2) returns 108 because the key "eur" was already stored on day 1. rate_good stores ("eur", 1) and ("eur", 2) as separate keys and returns each day's own rate.
Before you add a cache
- ▸The result depends on the arguments alone: the function reads no clock or file, and no global changes its answer
- ▸The same arguments really do repeat; unique ids gain nothing and fill memory
- ▸Stored results stay true for as long as the cache lives, such as a single batch run
- ▸The number of distinct keys fits in memory: 3 currencies yes, 50 million user ids no
Where the dict is created decides whether the cache works at all. A cache = {} line inside the function runs on every call, so each call starts with an empty dict, the in check always fails, and no lookup is ever saved.
What does this program print?
Every recursive function has 2 parts. The base case answers directly, without calling itself, for input small enough to need no further splitting. The recursive case calls the function on a smaller piece and builds its answer from the result. Each call gets a frame of its own, with its own local variables, and a frame waits until the call it made returns.
def factorial(n):if n <= 1:return 1return n * factorial(n - 1)print("5! =", factorial(5))
factorial(5) stacks 5 frames, and each waits for the call below it to return
factorial(1) is the base case and returns 1 without calling anything. Then the frames close from the bottom up: factorial(2) returns 2 and factorial(3) returns 6. By the time factorial(5) returns 120, factorial(4) has already returned 24. Without the base case the calls would never stop descending.
Nested lists of any depth
def sum_nested(data):total = 0for item in data:if isinstance(item, list):total += sum_nested(item)else:total += itemreturn totalnested = [1, [2, 3], [4, [5, 6]], 7]print("Sum of nested:", sum_nested(nested))
Each inner list opens a deeper frame, and the subtotals add up as those frames return
The loop covers a single level, and the recursive call covers everything below it. A number is a leaf and adds itself; a list hands its contents to a fresh call. The base case here is implicit: a list holding no inner lists finishes its loop without calling sum_nested again. The same 8-line function sums [1, 2] or a list nested 40 levels deep, and for this input the total is 28.
Dicts and lists mixed together
The empty items list contributes 0 because its loop never runs, and the bare 7 counts as 1 leaf because it falls through to the last return. No extra code handles either edge case; the structure of the function covers them.
What does this program print, line by line?
The call stack has a ceiling
Every waiting frame takes memory, so Python caps how many can be open at once and raises RecursionError past the cap; sys.getrecursionlimit() reports the current cap. A missing or unreachable base case hits that ceiling within a fraction of a second. Nested payloads rarely go deeper than a few dozen levels, so recursion suits them. A chain of 100,000 records, each pointing to the next, belongs in a while loop.
Recursion meets a memo dict
A payload nests its amounts at different depths, and many of them share a currency. The walker below recurses through dicts and lists until it reaches a dict holding an amount, which is its base case, and converts that amount through cached_rate from the memoization section. Any other leaf, such as an id string, adds 0.
The walker finds 4 amounts, 3 inside order lines and 1 directly under the payload, and returns 4040 US cents. The euro lines contribute 1080 and 2160; the dollar amounts add 500 and 300. Only 2 slow lookups ran, 1 per distinct currency, because the second euro amount found its rate already in rate_cache.
> Picture a nightly reconciliation job at Stripe over 2 million webhook events. Each event is a nested JSON payload holding an amount in the smallest currency unit, a currency code and a list of line items. The job converts every amount to US cents, totals them, and reports how many events it rejected and why.
amount_cents and currency as keyword-only parameters, so a call that passes them by position fails with TypeError before any event is totalled; every call site has to name amount_cents and currency.ValueError inside the helper, and the coordinator counts the event as rejected instead of adding 0 to the total.(currency, day), so 2 million events trigger a single slow lookup per distinct pair.* makes every later parameter name-only and / makes every earlier one position-only, so the call site names every value a reader could swap.-1 and None move the failure somewhere harder to find.Signatures that block bad calls, errors that speak up, testable helpers, dict caches and recursion into nested data.
- Category
- Python
- Difficulty
- advanced
- Duration
- 40 minutes
- Challenges
- 18 hands-on challenges
Topics covered: Keyword-Only and Positional-Only, Raising Errors From a Function, Helper Decomposition, Memoization with Dicts, Recursion Basics
Lesson Sections
- Keyword-Only and Positional-Only (concepts: Lambda)
Python fills parameters from positional arguments strictly left to right and never asks what the values mean. A call that passes 2 integers in the wrong order runs cleanly and hands back a wrong integer. This refund helper takes an amount and a processing fee, and both are counts of cents. Keyword-only: every parameter after * Positional-only: every parameter before / All 3 zones in a single signature
- Raising Errors From a Function (concepts: Functional Transforms)
What a quiet failure costs A raise stops the function and travels up Choosing the exception type
- Helper Decomposition (concepts: Functions)
When one function body parses and validates each row, then converts it and reports the result, the only way to check it is to build a whole batch to run through it and then read the printout. When the total comes out wrong, the fault could sit anywhere in it. Here is such a function for payment rows, with each rate stored as US cents per 100 units of the row's currency. Cut along the jobs Name each job in the body with a short phrase. Here the first job turns a row into a non-negative number of
- Memoization with Dicts (concepts: functools)
The key must hold every input Before you add a cache The pattern also handles failures correctly. If the expensive call raises, the line that stores into the cache never finishes, so nothing is stored and the next call with that key tries again. A lookup that failed on bad input is never remembered as an answer.
- Recursion Basics (concepts: Recursion)
A loop handles nesting only as deep as the loops you wrote. An event payload with lists inside dicts inside lists, to a depth that varies from row to row, needs a function that treats each inner piece the way it treats the whole. A recursive function does that by calling itself on a smaller part of its own input. Nested lists of any depth Dicts and lists mixed together Event payloads mix dicts and lists. The function below checks which kind of container it holds, recurses into every value inside