- Learn
- Computer Science & IT
- Programming
- Intermediate Python
- Python Functions and Decorators
Python Functions and Decorators
Advanced Functions and Decorators in Python
sorted, map and filter. Design flexible signatures with *args, **kwargs, keyword-only and positional-only parameters. Predict how Python finds a name with the LEGB rule, write closures that remember state, and build your own decorators, with and without arguments. Finish with the most useful tools in functools: caching, partial, reduce and singledispatch.IntermediateLesson 3 of 9 in Intermediate Python Course
What you will learn
- Treat functions as objects that can be named, stored, passed and returned, and use higher-order functions such as
sorted,mapandfilterwith key functions and lambdas.- Treat functions as objectsAssign functions to names, store them in data structures, pass them as arguments and return them from other functions.
- Sort, transform and select data with key functions and lambdasSort and pick items with key functions, write short lambda expressions, and transform or select data with
map,filteror a comprehension.
- Treat functions as objects
- Control how callers pass arguments: match arguments to parameters, collect and unpack any number of arguments, and require some arguments by name or by position.
- Match arguments to parametersExplain how Python binds positional arguments, keyword arguments and default values to parameters, and read the error when a call does not fit.
- Accept and forward any number of argumentsCollect extra arguments with
*argsand**kwargs, unpack sequences and dictionaries into a call, and pass arguments unchanged to another function. - Require keyword-only and positional-only argumentsUse
*and/in a signature to decide which arguments must be named and which must be given by position, and read a complete signature.
- Match arguments to parameters
- Predict which variable a name refers to with the LEGB rule, and change variables of an outer scope on purpose with
globalandnonlocal.- Find which variable a name refers toUse the LEGB rule to resolve names, explain when a name is local, and avoid shadowing and
UnboundLocalError. - Rebind outer variables with global and nonlocalUse
globalandnonlocalto assign to a variable of the module or of an enclosing function, and know when neither is needed.
- Find which variable a name refers to
- Build functions that remember variables from the scope where they were created, keep private state between calls, and avoid the late-binding trap in loops.
- Explain how closures capture variablesCreate inner functions that use variables of their enclosing function, follow what happens when the outer function returns, and inspect the captured variables.
- Keep state in closures and avoid late bindingWrite closures that remember data between calls, use
nonlocalto update it, and fix closures created in loops that all see the last value.
- Explain how closures capture variables
- Understand what the
@syntax does, write decorators that keep the decorated function's name and docstring, give decorators their own arguments, stack them, and use them for everyday tasks.- Write a basic decorator with functools.wrapsExplain the
@syntax, write a wrapper that passes on any arguments and the return value, and keep the original function's metadata withfunctools.wraps. - Give decorators arguments and stack themWrite decorator factories that take settings, decide the order of stacked decorators, and avoid the missing-parentheses mistake.
- Use decorators for everyday tasksApply decorators for timing, logging, counting, registration, validation and retrying, on functions and methods, and judge when a decorator helps.
- Write a basic decorator with functools.wraps
- Speed up repeated calls with caching, fix arguments in advance with
partial, combine a sequence into one value withreduce, and choose an implementation by type withsingledispatch.- Cache results with lru_cache and cacheMemoize functions with
functools.lru_cacheandfunctools.cache, read the cache statistics, and know which functions are safe to cache. - Fix arguments with partial and combine values with reduceCreate specialized functions with
functools.partial, fold a sequence into one value withfunctools.reduce, and choose a built-in instead when one exists. - Choose behavior by type with singledispatchTurn a function into a generic function with
functools.singledispatch, register implementations for different types, and predict which one runs.
- Cache results with lru_cache and cache
Python Functions and Decorators study guide
1Use functions as values
A function can be an input to another function, just as a string or a list can. That lets you separate a reusable operation from the choice of how to apply it. Start by passing function objects without calling them, then use small key functions to order data, transform values, and keep selected items. These same skills make the wrappers and function factories you will write later much easier to follow.
1.1 Pass behavior as a value
A def statement creates a function object and binds a name to it. The name is how you reach the object; parentheses are how you call it. This distinction lets your program choose an operation now and run it later.
Refer to a function or call it
def greet(name):
"""Build a greeting."""
return f"Hello, {name}!"
say = greet
message = say("Ana")
say = greet binds another name to the same function. It does not run the body. The call say("Ana") runs that body and returns 'Hello, Ana!', which becomes message. Both names still reach the same object, and say.__name__ remains 'greet'.
A callback is a callable handed to other code for that code to call. In sorted(words, key=len), the sorting code calls len on each word. Writing key=len("x") instead first computes 1. Sorting then tries to call that integer and raises TypeError. Read the expression on the right of key= before thinking about what sorting does.
Store a choice of operations
Functions fit in lists and dictionaries alongside other objects. A dictionary that selects a function is a dispatch table:
import operator
ops = {"+": operator.add, "-": operator.sub,
"*": operator.mul}
result = ops["*"](6, 7)
First, ops["*"] retrieves operator.mul. Next, (6, 7) calls it, producing 42. The dictionary stores functions, not the results of calling them. Adding an operation can mean adding one entry instead of another branch in a long if/elif chain.
Accept a function as an input
A higher-order function accepts a function, returns a function, or does both:
def apply_twice(func, value):
return func(func(value))
result = apply_twice(lambda n: n * 3, 2)
The inner call changes 2 to 6; the outer call changes 6 to 18. The caller chooses the operation, while apply_twice decides how to combine the calls. A function returned from another function is still an ordinary function object; you can store it and call it later.
Recognize callables and their attributes
A callable is an object that accepts a call with parentheses. Functions, built-ins such as len, methods, classes, and instances with __call__ can be callable. callable(len) is True; callable("len") is False. The string spelling a function's name is not that function.
Function attributes help describe the object. __name__ records its name, and __doc__ holds its docstring or None. For this signature:
def connect(host, port=443, *, timeout=10.0, retries=3):
return host, port, timeout, retries
connect.__defaults__ is (443,); connect.__kwdefaults__ is {'timeout': 10.0, 'retries': 3}. Either attribute is None when that kind has no defaults. You can also attach state such as greet.calls = 0; assigning the attribute alone does not make calls update it.
Key Takeaways
- A function name refers to an object; adding parentheses calls that object.
- Pass the callable itself when another function will call it.
- A dispatch table maps choices to functions.
- Higher-order functions accept or return functions.
- Function attributes describe the object even when several names refer to it.
1.2 Choose keys, transformations, and tests
A key function answers, "What should this item be compared by?" A transformation builds a new value, while a test decides whether to keep an item. All three accept data through calls, but their results serve different jobs.
Sort by a property
words = ["kiwi", "banana", "fig", "cherry"]
ordered = sorted(words, key=len)
longest = max(words, key=len)
ordered is ['fig', 'kiwi', 'banana', 'cherry']. The words stay intact; only their order changes. Sorting is stable, so equal-length words retain their input order. longest is 'banana', the first item with the largest key. min(words, key=len) gives 'fig'.
sorted returns a new list. words.sort(key=len) changes words in place and returns None. Assigning words = words.sort() therefore replaces your list with None.
For mixed-case simple words, key=str.lower compares lowercase forms while returning the original spellings. Without it, Python compares string character codes, so uppercase letters can come before lowercase letters.
Write a small key with lambda
A lambda creates a function from one expression: lambda n: n * n. The expression's value becomes the return value. There is no return statement. A conditional expression such as lambda n: "even" if n % 2 == 0 else "odd" is valid; an if block, assignment with =, or try statement is not.
people = [("Ana", 34), ("Ben", 28), ("Chloe", 34)]
ordered = sorted(people, key=lambda p: (-p[1], p[0]))
The tuple key compares negative age first, then name. The result is [('Ana', 34), ('Chloe', 34), ('Ben', 28)]. Negating the numeric field reverses age order without reversing names. reverse=True would reverse the entire tuple ordering.
operator.itemgetter(1) reads an indexed field; operator.attrgetter("name") reads an attribute. Use these when they express the key clearly. For a reusable operation with a meaningful name or several steps, use def. A lambda is not faster, and its recorded name is '<lambda>'.
Transform and keep selected items
upper = map(str.upper, ["a", "b"])
first = list(upper) # ['A', 'B']
second = list(upper) # []
map returns a lazy iterator: it computes results when consumed and is then exhausted. With several input iterables it takes one value from each and stops at the shortest. list(map(operator.add, [1, 2, 3], [10, 20])) is [11, 22].
filter is also lazy. It keeps original items whose test returns a truthy value. list(filter(lambda n: n % 2 == 0, range(10))) gives [0, 2, 4, 6, 8]. filter(None, values) keeps truthy values directly, removing items such as 0, "", and None.
A comprehension often reads clearly when the operation needs a lambda: [n for n in range(10) if n % 2 == 0]. A named function often fits map well. For older two-item comparison functions, functools.cmp_to_key(compare) adapts negative/zero/positive results to a sorting key; a direct tuple key is usually simpler.
Key Takeaways
- A key changes what is compared, not the items returned.
- Stable sorting keeps the input order among equal keys.
- A lambda contains one expression; use
deffor a named or multi-step operation. maptransforms items;filterkeeps items that pass a truth test.- Both
mapandfilterreturn lazy, exhaustible iterators. reverse=Truereverses the complete key ordering, including tie-breakers.
2Design flexible function signatures
A signature is a contract between a function and its callers. The position of each parameter, its default, and the separators in the definition determine which calls fit. Learn to trace that matching before the body runs, then collect or unpack arguments when their number varies. A clear signature also makes wrappers easier to trust: they can pass a call through without accidentally changing its meaning.
2.1 Bind arguments and create safe defaults
A parameter is a name in a definition; an argument is a value supplied in a call. Before running the body, Python matches those values to the parameters. A binding error raises TypeError before any body code executes.
Trace a call from left to right
def book_room(guest, nights=1, breakfast=False):
return guest, nights, breakfast
booking = book_room("Ana", breakfast=True)
The positional argument fills guest. The keyword fills breakfast by name. Nothing fills nights, so it receives its default, 1. The result is ('Ana', 1, True). Keywords can appear in any order: book_room(nights=2, guest="Ben") binds the same named slots regardless of their written order.
Explicit positional arguments must precede keyword arguments. book_room(guest="Ana", 2) is a SyntaxError, so no call takes place. An unpacked iterable is allowed after a keyword: for def f(a, b): return a, b, f(b=2, *[1]) is valid. Writing f(*[1], b=2) makes the order easier to read.
Use the failure to locate the problem
| Call | Binding problem |
|---|---|
book_room() | Required guest is missing. |
book_room("Ana", guest="Ben") | guest gets two values. |
book_room("Ana", night=2) | night is not an accepted keyword. |
book_room("Ana", 2, True, 4) | There are too many positional arguments. |
A default fills an empty slot; it never overrides a supplied argument or excuses a duplicate. Among parameters that can be filled by position, required parameters must precede parameters with defaults. def f(a=1, b): ... cannot be compiled.
Defaults are created when def runs
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
first = add_tag("a")
second = add_tag("b")
The empty list is created once, when the definition runs. Both calls use that same list, so second is ['a', 'b']. first now refers to that changed list too. A new call does not rebuild the default expression.
Use a fresh object inside the body when calls should be independent:
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
The None check creates a list only when the caller omitted it or passed None. An explicitly supplied list is still used and changed. Avoid if not tags: an empty list supplied by the caller is falsey, but it may be the exact list the caller wants updated.
Numbers, strings, and None cannot be mutated. A tuple containing a list can still share that inner list, so an immutable outer container alone does not make a default safe.
Inspect the contract
help(book_room) shows its documentation and signature. inspect.signature(book_room) from the inspect module displays (guest, nights=1, breakfast=False). Default values are stored on the function in __defaults__ and __kwdefaults__. Read the signature before debugging the body: a rejected call never reaches it.
Key Takeaways
- Bind positional values, then keywords, then defaults for unfilled parameters.
- A missing, duplicate, or unexpected argument prevents the body from running.
- Defaults are evaluated when the definition runs, not for every call.
- Use
Noneand create a mutable default inside the body when calls need fresh state. inspect.signatureshows the function’s call contract.
2.2 Collect, unpack, and forward arguments
Stars have opposite jobs in a definition and a call. In a definition they collect extra arguments into containers. In a call they spread container contents into individual arguments. The names args and kwargs are conventions; the stars determine the behavior.
Collect extra inputs
def total(*numbers):
return sum(numbers)
def build_profile(name, **details):
return name, details
total(4, 5, 6) binds numbers to (4, 5, 6) and returns 15. total() binds an empty tuple and returns 0. build_profile("Ana", city="Lima", age=34) binds the ordinary name first, then collects {'city': 'Lima', 'age': 34} in details. Extra keyword names are strings, and their order is preserved.
The order in a definition is ordinary parameters, *args, keyword-only parameters, and finally **kwargs. There can be at most one collecting parameter of each kind. No parameter may follow **kwargs.
Spread containers into a call
def dist(x, y):
return (x * x + y * y) ** 0.5
point = {"x": 3, "y": 4}
a = dist(**point)
b = dist(*[3, 4])
Both results are 5.0. * consumes the iterable in order and supplies positional values. ** supplies keyword values from a mapping; its keys must be strings. Without **kwargs in the target signature, those keys must match accepted parameter names. dist(**{"x": 3, "z": 4}) fails because z is unexpected.
Passing a container directly is different. total([4, 5, 6]) creates a one-item tuple containing a list; sum then tries to add that list to its numeric starting value and fails. total(*[4, 5, 6]) supplies three numbers.
Forward the original call
def call_logged(target, *args, **kwargs):
print(f"Calling {target.__name__}")
return target(*args, **kwargs)
answer = call_logged(dist, 3, y=4)
The helper stores args as (3,) and kwargs as {'y': 4}. It then unpacks both into dist, preserving the argument values and their positional or keyword roles. return passes the result back to the original caller. Writing target(args, kwargs) would send two container objects instead.
Detect collisions before the body
Several unpackings can appear in one call: f(*first, *second, **options). Each ordinary parameter must still get no more than one value. dist(3, **{"x": 4, "y": 0}) assigns x twice and raises TypeError.
Dictionary merging has a different rule. {**{"a": 1, "b": 2}, **{"b": 3}} produces {'a': 1, 'b': 3} because later keys replace earlier ones. Passing two ** mappings with the same keyword to a function does not use that replacement rule; the call fails.
With def label(name, /, **details), the first parameter is positional-only. label("item", name="public") can therefore collect the separate keyword name in details. Without /, that call duplicates the ordinary parameter. Prefer explicit names for fixed inputs: a broad **kwargs can quietly collect a misspelling such as timout.
Key Takeaways
- A starred parameter collects extra positionals in a tuple; a double-starred parameter collects extra keywords in a dictionary.
- Stars in a call unpack containers into arguments.
- Forward with
target(*args, **kwargs)and return its result. - Duplicate keyword names fail in calls even though later keys win in dictionary merging.
- Use explicit parameters when the accepted inputs are fixed.
- A positional-only name can also appear independently inside
**kwargs.
2.3 Control how callers supply each value
Some values are clearest by position; options are often clearest by name. Python lets you enforce those choices in the definition. The separators / and * are instructions for binding arguments, not values callers pass.
Require named options
def connect(host, port=443, *, timeout=10.0, retries=3):
return host, port, timeout, retries
connect("example.com", timeout=2.5) works. connect("example.com", 443, 5) fails because timeout is keyword-only. The bare * collects nothing; it marks the point after which parameters need names. An option such as retries=3 has a default, but keyword-only parameters can also be required.
def export(data, *, format):
return format, data
export([1, 2], format="csv") works; export([1, 2]) lacks the required keyword-only format. A default controls whether a value may be omitted. The star controls how a supplied value must be written. These are separate choices.
After *args, subsequent named parameters are also keyword-only:
def report(title, *lines, sep="\n"):
return sep.join((title, *lines))
report("Todo", "milk", "eggs", sep=" | ") returns 'Todo | milk | eggs'. Supplying " | " as another positional value adds another line; it does not fill sep. A bare star must have a named parameter after it, so def f(*): ... is invalid.
Require positional values
Parameters before / are positional-only:
def area(width, height, /):
return width * height
area(3, 4) returns 12. area(width=3, height=4) fails. Positional-only parameters let an author rename internal parameter names without breaking keyword calls, because those keyword calls were never allowed. They can also leave the same spelling available as a key in **kwargs.
Read a complete signature
def full(a, /, b, *args, c, d=0, **kwargs):
return a, b, args, c, d, kwargs
result = full(1, 2, 3, 4, c=5, e=6)
Read the definition in zones:
| Zone | Binding in this call |
|---|---|
Before /: positional-only | a=1 |
Between / and *args: positional or keyword | b=2 |
| Extra positionals | args=(3, 4) |
Named parameters after *args | c=5, d=0 |
| Remaining keywords | kwargs={'e': 6} |
Leaving out c raises TypeError; **kwargs does not make a required named parameter optional. Passing b twice still fails even though extra arguments can be collected.
Documentation uses these same separators. inspect.signature(sorted) shows (iterable, /, *, key=None, reverse=False): the data is positional-only, while key and reverse must be named. inspect.signature(len) shows (obj, /). The valid call is len([1]), not len(obj=[1]).
Key Takeaways
/makes earlier parameters positional-only.- A bare
*or*argsmakes later named parameters keyword-only. - A keyword-only parameter without a default is required.
- Signature separators govern how values are supplied; defaults govern whether they may be omitted.
3Apply Python's scope rules
A name does not carry one value everywhere in a program. Python resolves it in a particular scope, and an assignment inside a function can change how every use of that name is interpreted. Trace where a name is bound before changing its value. The distinction between changing an object and rebinding a name will explain both common scope errors and the state kept by closures.
3.1 Follow name lookup and diagnose local errors
A namespace maps names to objects. A scope determines where names can be used. For ordinary names inside functions, Python searches local, enclosing function, global module, and built-in scopes, in that order: LEGB. The first binding found wins.
Trace the nearest binding
x = "global"
def outer():
x = "enclosing"
def inner():
return x
return inner()
outer() returns 'enclosing'. inner has no local x, so it reaches the enclosing function's binding. If inner assigned its own x = "local" before returning it, that local binding would win. If neither function bound x, the module's 'global' would be used. A name absent from every applicable scope raises NameError.
The global scope belongs to the module where the function was defined. It is not whichever function happens to call it. Passing a function around does not move the scope in which it resolves its names.
Assignment makes a name local throughout the function
count = 0
def bump():
count += 1
return count
Calling bump() raises UnboundLocalError. The assignment makes count local to the whole function. += first needs the old local value, but none has been assigned. Python does not fall back to the global count after deciding that the name is local.
This decision happens when the function is compiled. Moving an assignment below a read does not help. Parameters, loop targets, imports, nested def and class statements, and as targets also bind names. A read-only function such as def peek(): return count + 1 can use the global and returns 1.
Changing an object differs from binding a name
items = []
def add_item(value):
items.append(value)
items.append(value) reads the module binding and changes the list. It does not assign to items, so it works without a declaration. Changing the line to items += [value] introduces assignment to the name; inside this function it would raise UnboundLocalError.
Blocks and special scopes
An if, for, while, with, or try block does not introduce a new scope. After for i in range(3): pass, i is still 2 in the surrounding scope. Comprehensions have their own scope for their iteration variable: after k = "outer" and [k for k in range(3)], the outer k remains 'outer'.
A class body has its own namespace, but it is not an enclosing function scope for methods. To access an instance attribute, write self.name; use the class name to access a class attribute when appropriate. A bare name in a method does not automatically find an attribute declared in the class body.
Keep built-ins reachable
Assigning sum = 0 shadows the built-in sum. A later sum([1, 2]) tries to call that integer and fails. Choose names such as total, values, and text instead of sum, list, and str. At an interactive module prompt, del sum removes the shadowing global binding so the built-in can be found again.
Key Takeaways
- LEGB finds the nearest applicable binding.
- Assignment makes a name local throughout a function unless a declaration changes that rule.
- An unfilled local raises
UnboundLocalError; lookup does not continue outward. - Mutation reads a binding and changes its object; assignment rebinds a name.
- Ordinary control-flow blocks do not create a scope.
- A class namespace is not an enclosing function scope for methods.
3.2 Choose global, nonlocal, or no declaration
Reading an outer binding needs no declaration. Assigning to it from a nested function does. Use global for a module binding and nonlocal for an existing binding in an enclosing function.
Rebind a module variable
count = 0
def bump():
global count
count += 1
return count
The declaration makes count refer to the module variable throughout bump. Calling it twice returns 1, then 2, and leaves the module's count at 2. If a global name does not exist, assigning to it after global creates the module binding.
The declaration must precede uses of the name in that function. Printing count and only then declaring global count is a SyntaxError. The statement is a rule for how the function's names are compiled, not an instruction that takes effect only after execution reaches it.
Rebind an enclosing function variable
def outer():
total = 0
def add(n):
nonlocal total
total += n
return total
add(5)
return add(7)
outer() returns 12. The inner add changes total in the nearest enclosing function that binds it. Without the declaration, total += n would make a new local total in add, whose old value could not be read.
nonlocal needs an existing enclosing function binding. A module variable alone cannot satisfy it, and nonlocal cannot create a missing outer name. Invalid uses are rejected when the code is compiled, even before any call.
| Choice | Where assignment goes | Existing binding required? |
|---|---|---|
| No declaration | Current function's local name | No |
global name | Defining module's namespace | No |
nonlocal name | Nearest enclosing function binding | Yes |
Both declarations apply to the function containing them. They do not change how unrelated functions treat the same spelling.
Avoid a declaration for mutation
def make_writer():
lines = []
def write(line):
lines.append(line)
return len(lines)
return write
write reads lines from the enclosing function and mutates the list. It needs no nonlocal. Replacing the list with lines = lines + [line] would assign to the name and would need nonlocal lines.
The same distinction applies to dictionary item assignment: settings["mode"] = "dark" changes an object; it does not rebind settings. Focus on the target of the assignment, not simply on whether the line contains an equals sign.
Make dependencies easy to see
A function that changes module state depends on earlier calls, which means callers and tests must track that history. When state is unnecessary, accept values as parameters and return new values. Read-only module constants such as MAX_RETRIES = 3 are straightforward to use without global. When one function needs to keep a small amount of changing state, an enclosing function and nonlocal keep that state near the code that updates it.
Key Takeaways
globaldirects a function’s binding to its module.nonlocalselects the nearest existing enclosing function binding.- Neither declaration is needed just to read an outer value or mutate its object.
- Declare a name before using it in that function.
4Write and use closures
A function factory can configure an operation once and return a function ready to use. The returned function can keep access to the settings and state created by the factory. Follow those shared variables through a few calls, then see why a loop can make several functions read the same final value. The fix depends on whether you want live shared state or a separate setting for each function.
4.1 Keep access to an enclosing variable
A closure combines an inner function with the enclosing variables it uses. Those variables remain accessible after the outer function returns. This lets you create a function with settings already attached through its surrounding scope.
Build two configured functions
def make_multiplier(factor):
def multiply(n):
return n * factor
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
Calling make_multiplier(2) first creates a local factor bound to 2. The inner def creates a function that needs this enclosing variable. return multiply hands that function object to the caller. It does not call it.
The factory call has finished, but double(5) can still read factor, so it returns 10. Calling the factory again creates a different local binding. triple(5) reads its own factor, 3, and returns 15. Separate factory calls give the closures separate settings.
Inspect what is captured
A captured variable is a free variable of the inner function: that function uses it but does not bind it locally. Python keeps its binding in a cell. For double, double.__code__.co_freevars is ('factor',) and double.__closure__[0].cell_contents is 2.
A function with no captured enclosing variables has __closure__ equal to None. Merely nesting a definition does not guarantee a captured variable. Global and built-in names are resolved at call time, without being stored in the function's closure cells.
Capture a variable, not a frozen copy
def make_reader():
value = 1
def read():
return value
value = 2
return read
reader = make_reader()
reader() returns 2. The inner definition did not take a snapshot of 1; it kept access to the binding that the outer function later changed. Several closures created in one factory call can share that same binding. This is useful for state, but it also explains late binding in loops.
Adapt a setting to a callback
def distance_from(target):
return lambda n: abs(n - target)
ordered = sorted([1, 9, 4, 6], key=distance_from(5))
distance_from(5) returns a one-argument key function. Sorting calls it on each item, producing distances 4, 4, 1, and 1. The result is [4, 6, 1, 9]: stable sorting preserves the original order within both ties. Parentheses are correct on the factory here because sorting needs its returned function, not the factory itself.
Lambdas follow the same capture rules as functions written with def. For example, a greeting factory can return lambda name: f"{prefix}, {name}!", keeping access to its prefix parameter.
Use a closure for one configured behavior or a small amount of private state. If several related operations must expose and update the same state, a class often makes that relationship clearer. Closures also supply the remembered original function inside a decorator wrapper.
Key Takeaways
- A closure keeps access to enclosing function variables after the outer call finishes.
- Each factory call creates fresh local bindings.
- Captured variables are live bindings, not frozen copies.
- Globals are looked up at call time and are not captured in closure cells.
- A factory call can return the callback another function needs.
4.2 Update private state and bind loop settings
A closure can remember what earlier calls did. Decide whether each call will mutate an existing object or rebind a stored name. Then check which calls share that state.
Store readings in a list
def make_averager():
readings = []
def average(value):
readings.append(value)
return sum(readings) / len(readings)
return average
avg = make_averager()
For temperature readings in degrees Celsius, avg(18), avg(21), and avg(24) return 18.0, 19.5, and 21.0. Each call appends to the same captured list. No nonlocal is needed because the name readings is only read, while its list is mutated.
Keep a fixed amount of state
The list grows with every reading. If you need only the running average, store a total and a count:
def make_averager():
total = 0
n = 0
def average(value):
nonlocal total, n
total += value
n += 1
return total / n
return average
The same three calls produce the same averages. The two numbers are rebound, so both names need nonlocal. Leaving it out makes the first += read an unfilled local and raise UnboundLocalError. A counter uses the same idea with one captured count. Two calls to the counter factory create independent counters; assigning a second name to one returned counter shares its state.
Diagnose late binding in a loop
def make_steps():
funcs = []
for step in (1, 10, 100):
funcs.append(lambda n: n + step)
return funcs
funcs = make_steps()
results = [f(1) for f in funcs]
results is [101, 101, 101]. Every lambda reads the same enclosing step, whose final value is 100. The loop did not create a new scope for each iteration. A comprehension such as [lambda: i for i in range(3)] similarly gives functions that later all return 2.
Three ways to give each function its intended setting are:
- A default evaluated during each definition:
lambda n, step=step: n + step. This gives[2, 11, 101]for calls with1; callers can still override the extra parameter. - A factory that creates a new binding on each call:
make_adder(step)returns an inner function reading its ownstep. partial(operator.add, step)fromfunctools, which stores the current argument object when constructed.
Hidden variables can refer to shared objects
Creating readings = [] inside the factory keeps ordinary outside code from reaching it by a local variable name. Passing an outside list into a factory is different: the caller still holds that list and can mutate it. The closure sees those changes because both references reach one object. A closure protects where a name is bound; it does not copy every object it captures. Keep state inside the factory when only the returned function should manage it.
Key Takeaways
- Mutating a captured list needs no
nonlocal; rebinding a captured number does. - A total and count can replace a growing list when only an average is needed.
- Closures made in one loop can share the loop variable and read its final value.
- Defaults, separate factory calls, and
partialcan preserve each intended loop setting. - Capturing an outside mutable object leaves it shared with its other holders.
- Two names for one closure share state; separate factory calls usually create separate state.
5Write decorators
Decorators put shared behavior around a function while leaving its main task easy to read. Their mechanics combine the skills you already have: pass a function as a value, capture it in a closure, and forward its arguments. Trace both the moment a decorator is applied and the later calls to its wrapper. Then add settings, stack wrappers in a deliberate order, and choose useful jobs for them.
5.1 Wrap a function and preserve its identity
A decorator takes a function and returns the object its name will refer to. Most return a wrapper function that adds behavior around the original call. Some return the original function unchanged or another callable object.
Build a forwarding wrapper
from functools import wraps
def shout(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
Expand the at-sign syntax
@shout
def hello(name):
return f"hello, {name}"
This has the same effect as defining hello and then assigning hello = shout(hello). The decorator receives the original function object. The name hello is rebound to the returned object; the original function's code is not edited.
During decoration, shout creates the wrapper and returns it. The wrapper captures func, preserving access to the original. Later, hello("Ana") collects the argument, calls the original with it, receives 'hello, Ana', and returns 'HELLO, ANA'.
The two returns have different jobs. return wrapper gives the caller a function to run later. The inner return gives each future caller the decorated result. Returning wrapper() would run it during decoration. Omitting the outer return binds hello to None; omitting the inner return discards the result and makes each successful decorated call return None.
Separate decoration time from call time
The decorator runs when the decorated definition executes, usually when its module is imported. The wrapper runs when someone calls the decorated name. Put setup such as creating a counter in the decorator; put per-call work such as incrementing it inside the wrapper. A print outside the wrapper happens during setup, even if the function is never called.
*args, **kwargs lets the wrapper accept and forward varied call shapes. A wrapper defined as wrapper(name) can handle a single name but rejects a call with an extra keyword that the original might accept. Forwarding does not make invalid calls valid: the original still checks its own signature when called.
Keep useful metadata
Without wraps, the public function's __name__ would be 'wrapper', and its docstring would describe the wrapper or be None. @wraps(func) copies the original name, qualified name, module, docstring, and annotations, updates the wrapper's attribute dictionary, and sets __wrapped__ to the original. From Python 3.12 it also copies __type_params__ by default.
hello.__name__ is now 'hello'. hello.__wrapped__("Ben") bypasses this wrapper and returns 'hello, Ben'. Tools such as help and signature inspection can use that link. wraps preserves metadata; the wrapper's code still determines argument forwarding and return behavior.
A registration decorator can instead store func in a dictionary and return func. It adds a setup action without inserting a wrapper into future calls.
Key Takeaways
@decoraterebinds a function name todecorate(original).- Return the wrapper object during decoration and the desired result during each call.
- Forward with
*args, **kwargsso supported call shapes reach the original. - The decorator runs at definition time; its wrapper runs at call time.
wrapspreserves metadata and exposes the wrapped function through__wrapped__.
5.2 Configure decorators and trace their order
A decorator with settings needs a first call that builds the decorator. That creates three jobs: receive settings, receive the original function, and handle each later call. Name the layers by their jobs to keep the returns clear.
Build a decorator factory
from functools import wraps
def repeat(times):
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
return [func(*args, **kwargs)
for _ in range(times)]
return wrapper
return decorate
@repeat(3)
def roll():
return "x"
repeat(3) returns decorate, which remembers times=3. decorate(roll) returns the wrapper, which remembers func. A later roll() calls the original three times and returns ['x', 'x', 'x']. The compact expansion is roll = repeat(3)(roll).
Writing @repeat passes the function itself as times and binds its name to decorate. It does not mean "use the default settings." A factory needs parentheses even with no explicit settings, such as @repeat() when times has a default.
A decorator can deliberately support both forms:
def emphasize(func=None, *, mark="*"):
if func is None:
return lambda f: emphasize(f, mark=mark)
@wraps(func)
def wrapper(*args, **kwargs):
return mark + func(*args, **kwargs) + mark
return wrapper
Here @emphasize passes a function directly, while @emphasize(mark="_") first returns a decorator configured with the mark. Both routes eventually build a wrapper.
Expand a stack before tracing a call
def brackets(func):
@wraps(func)
def wrapper(*args, **kwargs):
return "[" + func(*args, **kwargs) + "]"
return wrapper
def parens(func):
@wraps(func)
def wrapper(*args, **kwargs):
return "(" + func(*args, **kwargs) + ")"
return wrapper
@brackets
@parens
def word():
return "hi"
Suppose parens adds ( and ) around a returned string and brackets adds [ and ]. The assignment is word = brackets(parens(word)). The bottom decorator is applied first. At call time the outer brackets wrapper enters first, then calls the parens wrapper, which calls the original. Results return outward, producing '[(hi)]'. Swapping the stack gives '([hi])'.
A cache stores earlier results so a repeated call can skip the original computation.
| Stack, top to bottom | What a cache hit reaches |
|---|---|
@timed, @lru_cache() | Timing wrapper, then cache |
@lru_cache(), @timed | Cache returns before timing wrapper |
Order can decide whether work happens at all. With timing outside caching, hits are timed too. With caching outside timing, only cache misses enter the timing code. Access checks generally belong outside a cache so a stored result does not bypass a check on a later call.
Put state in the intended layer
State created inside decorate belongs to that decoration. Two decorated functions get separate counters if each counter is created there. A setting created in the factory can be shared when one returned decorator is reused: twice = repeat(2) followed by @twice on two functions shares the captured times. Read-only settings work well this way; a mutable object created in the factory would also be shared by both wrappers.
Key Takeaways
- A decorator factory returns the decorator that receives the function.
- A factory normally needs parentheses, including when all settings have defaults.
- A stack expands from the bottom up; calls enter the top wrapper first.
- Wrapper order can determine whether timing, checking, or counting happens on cache hits.
- State created per decoration is separate; state created in a reused factory call can be shared.
- A decorator can support bare and configured forms if its code handles both routes.
5.3 Add shared behavior with a clear contract
Decorators work well for behavior used consistently across several functions: timing, logging, counting, registration, validation, and retries. Choose a wrapper whose effect callers can predict, and keep the original return value unless changing it is the decorator's stated purpose.
Time or count calls
from functools import wraps
from time import perf_counter
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {perf_counter() - start:.4f} s")
return result
return wrapper
perf_counter measures intervals in seconds: subtract two readings. This wrapper prints after a successful call; if the original raises, execution leaves before the print. To count attempted calls, increment wrapper.calls before calling the original and initialize wrapper.calls = 0 once in the decorator, before returning it. Each decorated function then has its own counter attribute.
A logging wrapper can display positional arguments with repr(a) and keywords with f"{k}={v!r}", call the function, and display its result. Keep logs free of passwords or other private values. Logging before and after a call has the same exception-flow issue as timing: code after a failed call is not reached.
Register without wrapping
PLUGINS = {}
def register(func):
PLUGINS[func.__name__] = func
return func
@register
def export_csv(data):
return ",".join(map(str, data))
The dictionary is populated when the definition executes. PLUGINS["export_csv"]([1, 2]) calls the stored function. Because the decorator returns the original, ordinary calls to export_csv gain no wrapper layer.
Validate the arguments you mean to check
A numeric validator can reject values at or below zero before calling an area function. A generic forwarding wrapper also works on instance methods because self arrives as the first positional argument. A validator that inspects every argument must handle that receiver separately: an instance is not a numeric measurement. A method wrapper can use def wrapper(self, *args, **kwargs), validate only the measurement arguments, and then call func(self, *args, **kwargs).
Retry selected failures
def retry(times, exceptions=(Exception,)):
if times < 1:
raise ValueError("times must be positive")
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(times):
try:
return func(*args, **kwargs)
except exceptions:
if attempt == times - 1:
raise
return wrapper
return decorate
@retry(3, exceptions=(ConnectionError,)) allows at most three attempts. Success returns immediately. The final matching failure is re-raised; an unlisted exception escapes immediately. Retrying can repeat work already performed before a failure, so use it where repeated attempts are safe.
A callable class instance can also wrap and count function calls. Built-in decorators such as staticmethod, classmethod, and property support method-related behavior. Prefer a plain call inside one function when shared wrapping would obscure a simple one-place operation.
Key Takeaways
- Use a decorator for predictable behavior shared across functions.
- Measure elapsed time by subtracting
perf_counterreadings. - Registration can return the original function unchanged.
- An argument-inspecting method wrapper must account for
self. - A retry wrapper returns on success, catches selected failures, and re-raises after its last attempt.
- A callable object can serve as the decorated result.
6Use the functools module
The functools module packages several patterns that would otherwise require custom closures and wrappers. Choose a tool by its job: remember results, prefill arguments, fold items into one result, or select behavior by type. Trace the calls each tool actually makes. Their convenience comes with specific contracts about argument order, shared objects, and which part of a call determines its behavior.
6.1 Reuse computed results with a cache
Memoization stores a call's result under its arguments. A repeated call can return that result without executing the original body. A cache miss computes and stores a result; a cache hit retrieves an entry already present.
Choose a cache size
from functools import lru_cache, cache
@lru_cache(maxsize=128)
def square(n):
return n * n
lru_cache retains up to maxsize distinct call entries. When full, it discards the least recently used entry. The default size is 128; @lru_cache, @lru_cache(), and an explicit configured form are valid. @cache, available since Python 3.9, is the unbounded form, equivalent to lru_cache(maxsize=None).
For a fresh cache of size two, follow arguments 1, 2, 1, 3, 2. The first two miss. The third hits 1, making 2 least recently used. Adding 3 evicts 2; the final 2 therefore misses. The statistics are hits=1, misses=4, currsize=2.
Remove repeated recursive work
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
fib(30) is 832040. Without caching, this definition makes 2692537 calls because subproblems recur. Starting from an empty unbounded cache, each input from 0 through 30 is computed once. fib.cache_info() then shows CacheInfo(hits=28, misses=31, maxsize=None, currsize=31). Calling fib(30) again adds a hit, without entering the body.
cache_clear() empties entries and resets statistics. __wrapped__ reaches the original function without the outer cache check. These controls let you measure whether the cache is useful and reset it when needed.
Check the function's contract
Arguments must be hashable because the cache uses them as dictionary keys. A list fails with TypeError; a tuple works when its contents are hashable. A tuple containing a list is still unhashable.
Use caching when the result depends on the arguments and the body need not repeat side effects. A clock reading, random choice, or changing file value can become stale. Printing inside the body happens on misses, not hits. If callers expect a fresh reading or a fresh side effect every time, caching changes the behavior they need.
Notice shared result objects
@cache
def get_list(n):
return list(range(n))
a = get_list(3)
a.append(99)
The next get_list(3) returns [0, 1, 2, 99]: the cache returns the same object, not a copy. Return an immutable result such as a tuple, or copy before modifying it.
Calls with the same values written in different forms can occupy separate entries. typed=True also separates immediate argument types, such as 3 and 3.0; it does not recursively distinguish types inside a container. An unbounded cache holds arguments and results in memory until cleared or released. Use a size bound for a long-running workload with many distinct inputs. cached_property serves the separate pattern of storing a computed attribute per object.
Key Takeaways
- A hit skips the original body; a miss computes and stores a result.
- A bounded LRU cache evicts the entry least recently accessed.
cache_info()reports usage;cache_clear()removes entries and resets counts.- Arguments must be hashable, including the contents of tuples used as arguments.
- Cache stable computations whose side effects need not repeat.
- A cached mutable result is shared with later callers.
- Unbounded caches retain objects and can keep growing.
6.2 Prefill arguments and fold a sequence
partial and reduce solve different problems. partial makes a callable with some arguments already supplied. reduce repeatedly combines an accumulated result with the next item until one result remains.
Build a specialized callable
from functools import partial
basetwo = partial(int, base=2)
a = basetwo("10010")
b = basetwo("ff", base=16)
a is 18. The partial stores base=2, then supplies the string when called. A keyword supplied by the later caller overrides a stored keyword, so b is 255. The stored pieces are available as basetwo.func, basetwo.args, and basetwo.keywords: int, (), and {'base': 2}.
Stored positional values are prepended. partial(pow, 4)(3) computes 4 ** 3, giving 64. To fix a later parameter, use a keyword when the target allows it: partial(pow, exp=3)(4) also gives 64. A new positional value does not replace a stored positional value. If it also fills a parameter with a stored keyword, normal duplicate-binding rules still apply.
list(map(partial(round, ndigits=1), [2.345, 7.06])) is [2.3, 7.1]. The specialized callable fits a place that supplies one input at a time. A lambda can also reorder or compute arguments; choose it when prefilled arguments alone do not express the operation.
A partial stores the current argument objects at construction. That avoids later lookup of a loop variable, but it does not copy mutable objects. A later change to a stored list remains visible.
Fold left with an accumulator
import operator
from functools import reduce
value = reduce(operator.sub, [10, 3, 2])
The first step is 10 - 3, giving 7. The next is 7 - 2, giving 5. The accumulator is always the left argument to the combining function. This is a left-to-right fold, so changing the grouping can change the result for operations such as subtraction.
With an initial value, that value is the first accumulator:
letters = reduce(lambda acc, word: acc + len(word),
["kiwi", "fig", "plum"], 0)
Starting at 0, the accumulated totals are 4, 7, and 11. Without that initial 0, the first accumulator would be 'kiwi'; adding the next word's length would try to add a string and an integer.
Handle empty and one-item inputs
reduce(operator.mul, [1, 2, 3, 4], 1) gives 24. The initial 1 also makes an empty input return 1. Without an initial value, an empty input raises TypeError, while a one-item input returns that item without calling the combining function.
Use sum, math.prod, min, max, any, all, or str.join when one expresses the task directly. A custom fold is useful when no such operation fits, such as repeatedly merging dictionaries. Other functools helpers include wraps and update_wrapper for metadata, cmp_to_key for comparisons, and class-oriented tools such as partialmethod and total_ordering.
Key Takeaways
- A partial prepends stored positional arguments and combines stored keywords with later keywords.
- A later keyword overrides a stored keyword; later positional arguments do not replace earlier ones.
partialstores argument objects without copying them.reducefeeds the running result into the next left-to-right combination.- An initial value handles empty input and sets the accumulator’s starting type.
- Prefer a direct built-in operation when one expresses the task.
6.3 Select an implementation from the first argument
A generic function presents one callable name with implementations for different input types. singledispatch chooses an implementation from the type of the first positional argument. Other arguments are passed to that implementation but do not help select it.
Define a fallback and register cases
from functools import singledispatch
@singledispatch
def describe(value):
return f"something else: {value!r}"
@describe.register
def _(value: int):
return f"integer {value}"
@describe.register
def _(value: list):
return f"list of {len(value)} items"
@describe.register(float)
def _(value):
return f"float {value:.2f}"
The decorated base function supplies the fallback. describe(5) returns 'integer 5'; describe([1, 2]) returns 'list of 2 items'; describe(2.5) returns 'float 2.50'. With no string implementation, describe("hi") uses the fallback and returns "something else: 'hi'".
The bare @describe.register form reads the first parameter's type annotation. Without an annotation it cannot infer which type to register. The explicit form, such as @describe.register(float), supplies that type directly. A union annotation such as int | float registers both types from Python 3.11 onward.
The repeated name _ is a common choice for implementations called through the generic function. Rebinding _ for the next definition does not remove the earlier entry from the registry. The registry retains the function object.
Follow inheritance when there is no exact match
result = describe(True)
The result is 'integer True'. bool is a subclass of int, and there is no separate registered bool implementation. Dispatch finds the closest applicable parent implementation. Adding a bool registration would make boolean inputs use it while ordinary integers continue to use the int version.
describe.registry exposes the mapping of registered types to functions, including object for the fallback. describe.dispatch(bool) returns the function that would handle a boolean, without calling that implementation on a value.
Keep dispatch separate from ordinary binding
A call needs at least one positional argument. describe(value=3) raises TypeError even though the base definition names the parameter value: the dispatch wrapper needs the first positional value to choose an implementation.
For a generic function with two parameters, changing the second argument's type does not change the selected implementation. Each registered implementation still needs a compatible signature for the calls you support. Dispatch chooses a function; Python then binds that function's arguments normally.
Use this pattern to extend behavior by registering another type without editing a growing chain of isinstance tests. Registrations can be added from another module. For methods, functools offers singledispatchmethod, which handles method dispatch separately from this plain-function pattern.
Key Takeaways
singledispatchchooses by the first positional argument’s type.- The base function is the fallback for types without a more specific implementation.
- Register with an explicit type or an annotation the registration can read.
- Without an exact match, an applicable parent implementation can handle a subclass.
- Dispatch selection and the chosen function’s argument binding are separate steps.
Python Functions and Decorators examples
1Pass an operation, then use its results
12 steps
- 1IntroductionChoose behavior before running it
Suppose a report must support several ways to order its records. You can write the ordering process once and pass in the rule it should use. A function that accepts another function this way is a higher-order function, so one routine can serve many rules. We will first follow a function object without calling it, then use functions to compare and transform data. At each call, ask two questions: what value does the callable receive, and what does the surrounding code do with its result?
- 2ExampleCreate another name for one function
def add_three(n): return n + 3 adjust = add_threeThe definition creates a function; the assignment binds
adjustto that same object. No addition has happened yet.adjust(4)later returns7, andadjust.__name__is still'add_three'. The object's recorded name does not change each time another variable points to it. - 3ExplanationLet another function make the calls
def twice(func, value): return func(func(value)) answer = twice(add_three, 4)The caller supplies behavior as
func. The inner call adds three to4, producing7; the outer call adds three again, producing10.twiceis a higher-order function because it accepts a function. Its call sequence stays the same when the caller chooses a different operation. - 4ChallengePass the function or its result?
A helper expects a one-input callable as its first argument. Why does
twice(add_three(4), 1)fail?---reveal---
add_three(4)runs immediately and supplies the integer7. Insidetwice, Python tries to call that integer asfunc, raisingTypeError. Passadd_threeitself so the helper receives behavior it can call on its own input. - 5ConnectionStore the available operations
import operator ops = {"add": operator.add, "multiply": operator.mul} answer = ops["multiply"](3, 5)The dictionary lookup first retrieves a callable, then the final parentheses supply its arguments. This dispatch table chooses an operation by name and returns
15. The same pattern can choose a handler or export function without putting every operation inside one large branching function. - 6ExampleCompute keys without replacing the items
words = ["peach", "fig", "plum", "grape"] ordered = sorted(words, key=len)The keys are
5,3,4, and5. Sorting compares those lengths but returns the words:['fig', 'plum', 'peach', 'grape']. The equal-length pair keeps its input order because sorting is stable.sortedcreates a new list; the originalwordsstays in its existing order. - 7ExplanationGive each comparison two fields
rows = [("Lina", 7), ("Omar", 9), ("Aya", 9)] ordered = sorted(rows, key=lambda row: (-row[1], row[0]))The lambda returns one tuple per row. Negative scores put larger scores first; names then resolve the tie. The result is
[('Aya', 9), ('Omar', 9), ('Lina', 7)]. A lambda returns one expression, so no explicitreturnis written inside it. - 8ChallengeKeep the tie-breaker in the right direction
A key is
(score, name)and the call usesreverse=True. For equal scores, do names run in ascending or descending order?---reveal---
Descending. Reversal applies to the complete tuple ordering, including the name field. To put numeric scores in descending order but names in ascending order, use a key such as
(-score, name)without reversing the whole result. - 9ExampleConsume a transformation once
upper = map(str.upper, ["oak", "elm"]) first = list(upper) second = list(upper)The first conversion requests and collects the transformed strings, giving
['OAK', 'ELM']. The iterator has now been consumed, so the second conversion gives[]. With multiple input iterables,maptakes one value from each per call and stops when the shortest input ends. - 10ExplanationKeep items that pass a test
filterretains original values whose test result is truthy.list(filter(lambda n: n > 0, [-2, 0, 5]))gives[5]. WithNoneas the test, each item's own truth value decides: zero and empty strings are removed too.A comprehension such as
[n for n in values if n > 0]may read more directly when the test would otherwise need a lambda. Both forms express selection, not replacement. - 11ChallengeCombine selection with transformation
What does this produce?
result = list(map(len, filter(None, ["", "oak", "birch"])))---reveal---
[3, 5]. Filtering removes the empty string, keeping the two original nonempty words. Mapping then callslenon each remaining word. Each callback receives the output of the preceding stage, and the finallistconsumes the lazy results. - 12RecapTrace the role of each callable
When reading a higher-order call, identify the function object first, then follow its inputs and how its return value is used. A key guides comparison, a mapping function transforms, and a filter test selects. Use a named function, a short lambda, or an operator helper to express the behavior clearly. For lazy results, also track whether an earlier operation has already consumed the iterator.
2Read and test a complete signature
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionCheck the call before the body
- 2ExampleFill parameters from the call
- 3ChallengeFind the duplicate value
- 4ExampleNotice the shared default object
- 5TipCreate fresh state inside the call
- 6ExampleCollect the extra positionals
- 7ExplanationReverse the stars when making a call
- 8ChallengeRepair a forwarding helper
- 9Key InsightA merge and a call handle duplicates differently
- 10ExplanationRequire named options
- 11ExampleRead all signature zones
- 12ChallengeUse a name independently as metadata
- 13RecapTreat the signature as a binding map
3Locate the binding before changing it
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFind the name’s home
- 2ExplanationSearch in LEGB order
- 3ExampleAssignment changes the whole function’s lookup
- 4ChallengeA list update with no declaration
- 5TipDo not hide the built-in you need
- 6ExampleRebind a module value explicitly
- 7ExplanationUpdate the nearest enclosing function
- 8ChallengeChoose the target of an update
- 9ChallengeSeparate a block from a scope
- 10RecapName lookup and object changes are separate
4Build functions that remember
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionReturn a function with settings attached
- 2ExampleCreate the factory
- 3ExampleMake two separate settings
- 4Key InsightCaptured variables can change
- 5ChallengeInspect the captured setting
- 6ExampleCreate a persistent numeric total
- 7ConnectionKeep only the state the result needs
- 8ChallengeDistinguish an alias from another factory call
- 9ExampleBuild callbacks in a loop
- 10TipBind the intended setting while building
- 11ChallengeCapture a list shared with the caller
- 12RecapTrack bindings and shared objects
5Build and trace reusable decorators
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAdd behavior around the same task
- 2ExplanationExpand the decoration
- 3ExampleWrite the forwarding layer
- 4ExampleSeparate setup from calls
- 5ChallengeLocate the missing return
- 6TipPreserve metadata deliberately
- 7ExampleAdd the settings layer
- 8ChallengeCall the factory at the right time
- 9ExplanationTrace a stack from the inside out
- 10Key InsightLet order express the policy
- 11ExampleTime successful work
- 12ConnectionRegister without a wrapper
- 13ChallengeLeave the method receiver out of a numeric check
- 14ExplanationRetry only the failures you intend
- 15ChallengeCombine a counter and a cache
- 16RecapCheck every layer’s job
6Choose and trace functools helpers
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMatch the helper to the job
- 2ExampleWatch hits and misses
- 3ChallengeChoose the entry to evict
- 4ExplanationReuse subproblems in recursion
- 5Key InsightA cached value can remain shared
- 6ExampleStore a keyword for future calls
- 7ChallengeExpand the partial before binding
- 8ExampleFollow a left fold
- 9ExplanationStart with the right accumulator
- 10ExampleCreate a generic function
- 11ExplanationUse a specific case or a parent
- 12ChallengeIdentify the dispatching argument
- 13ChallengeSpot the missing input in a cache key
- 14ConnectionSeveral helpers still obey ordinary binding
- 15RecapChoose a helper by its contract
Python Functions and Decorators practice questions
Set 1: Read calls, names, and wrappers10 Practice Questions
Question 1 of 10
What does alias(4) return?
def offset(n):
return n + 7
alias = offset
Show answerHide answer
alias and offset refer to the same function object, so calling either with 4 runs the body and returns 11. Assignment does not call the function or store a previous result; it gives the object another name. The function's recorded name remains offset.Question 2 of 10
What must make_adder return so the caller receives a function?
def make_adder(amount):
def add(value):
return value + amount
# return statement here
Show answerHide answer
return add hands the function object to the caller without executing its body. The caller can then supply a value later, while the returned closure still reads amount. Calling add in the return statement would instead return the numeric result of that immediate call.Question 3 of 10
What does outer() return?
label = "module"
def outer():
label = "factory"
def read():
return label
return read()
Show answerHide answer
read has no local binding for label, so lookup reaches the enclosing function before the module. That enclosing binding holds "factory". The global value is not selected just because it was assigned earlier; lookup follows scope order, not assignment time across scopes.Question 4 of 10
What happens when advance() is called?
level = 6
def advance():
next_level = level + 1
level = 10
return next_level
Show answerHide answer
level anywhere in advance makes it local throughout that function. The first line therefore reads a local binding before it has a value, raising UnboundLocalError. It does not read the module's 6 and only become local when execution reaches the later assignment.Question 5 of 10
show(value=6) fail when show is a singledispatch generic function whose base definition is def show(value)?Show answerHide answer
value. Ordinary keyword binding in that base definition does not remove the generic wrapper's dispatch requirement.Question 6 of 10
What call supplies data as [3], enables strict, and uses the default limit?
def inspect_data(data, /, limit=5, *, strict):
return data, limit, strict
Show answerHide answer
data must be positional because it precedes /, while strict must be named because it follows *. Leaving limit unfilled selects its default of 5. Supplying True as the second positional argument fills limit and still leaves the required keyword-only strict missing.Question 7 of 10
What values are assigned to x, y, and z?
def counter():
n = 0
def tick():
nonlocal n
n += 1
return n
return tick
a = counter()
b = a
c = counter()
x, y, z = a(), b(), c()
Show answerHide answer
a and b name one closure and share its captured count, so their calls return 1 and 2. c comes from a new factory call with a fresh count and returns 1. Assigning a second name to an existing function does not create a fresh closure or reset its state.Question 8 of 10
What does this call return?
def pack(head, *tail, **labels):
return head, tail, labels
result = pack(*[7, 8, 9], unit="s")
Show answerHide answer
head takes 7, tail collects the remaining positionals as a tuple, and labels collects the extra keyword. Passing the list without the call's star would instead make the entire list the head.Question 9 of 10
What do a and b contain at the end?
def store(value, items=None):
if items is None:
items = []
items.append(value)
return items
a = store("sun")
b = store("rain")
Show answerHide answer
items, so each starts with None and creates a new list inside the body. The results are independent lists containing "sun" and "rain". Sharing a default value of None does not share the lists later created separately during those calls.Question 10 of 10
A retry_two decorator catches only ConnectionError, allows at most two attempts, and returns on success. What are a and b, and how many items are in events at the end?
from functools import cache
events = []
@cache
@retry_two
def send(n):
events.append(n)
if len(events) == 1:
raise ConnectionError("try again")
return len(events)
a = send(4)
b = send(4)
Show answerHide answer
2, which the outer cache stores. The next call hits that cache, returning 2 without entering the retry wrapper or appending. The failed attempt’s append remains: catching an exception does not undo a mutation.Set 2: Apply signatures and captured settings10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
How are the parameters bound by reserve("Noor", quiet=True)?
def reserve(name, seats=2, quiet=False):
return name, seats, quiet
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What does double(6) return with this decorator?
def observe(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
return wrapper
@observe
def double(n):
return n * 2
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
What name does the decorated function report, and what text does calling label.__wrapped__() produce?
from functools import wraps
def loud(func):
@wraps(func)
def wrapper():
return func().upper()
return wrapper
@loud
def label():
return "ready"
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
What declaration belongs in add to update the counter created by make_counter?
count = 100
def make_counter():
count = 4
def add():
# declaration here
count += 2
return count
return add
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
After these calls, what does a contain?
def record(item, items=[]):
items.append(item)
return items
a = record("oak")
record("pine")
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What does read() return?
def build():
setting = 3
def read():
return setting
setting = 8
return read
read = build()
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What are the values of a and b?
values = map(lambda n: n + 4, [2, 5])
a = list(values)
b = list(values)
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
compute(([1, 2],)), before its body can run?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What pair is produced by the final line?
from functools import singledispatch
@singledispatch
def label(value, detail):
return "base"
@label.register(int)
def _(value, detail):
return "integer"
@label.register(bool)
def _(value, detail):
return "boolean"
result = label(2, True), label(True, 2)
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
ConnectionError, returns on success, and re-raises the final matching failure. A wrapped function raises ConnectionError on its first call and ValueError on its second. How does the decorated call finish?Show answerHide answer
Save this lesson to see this answer.
Set 3: Trace shared state and wrapped calls10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
What is the value of result?
names = ["Ivo", "Mina", "Bo", "Sara"]
result = sorted(names, key=len)
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What is alias.__name__?
def finish(value):
return value + 1
alias = finish
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
What does put("r") return after this setup?
items = []
def put(value):
items.append(value)
return len(items)
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
reduce(operator.sub, [20, 4, 3], 2) return? Assume both names have been imported.Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
What is the result of the final call?
from functools import partial
parse = partial(int, base=8)
result = parse("21", base=10)
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Why does relay(6, right=4) fail?
def combine(left, right):
return left + right
def relay(*args, **kwargs):
return combine(args, kwargs)
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What does the final call return?
def make_average(values):
def average(value):
values.append(value)
return sum(values) / len(values)
return average
shared = []
avg = make_average(shared)
avg(12)
shared.append(30)
result = avg(18)
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
What is events after the final line?
events = []
def watch(func):
events.append("setup")
def wrapper():
events.append("enter")
result = func()
events.append("exit")
return result
return wrapper
@watch
def run():
events.append("body")
return 5
run()
run()
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What happens on the final call?
from functools import partial
def join(a, b, *, sep=":"):
return a + sep + b
left = partial(join, "x", sep="-")
result = left("y", b="z")
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
What does events contain at the end?
from functools import lru_cache
events = []
def log(func):
def wrapper(n):
events.append(n)
return func(n)
return wrapper
@lru_cache(maxsize=4)
@log
def cube(n):
return n ** 3
cube(2)
cube(2)
cube(3)
Show answerHide answer
Save this lesson to see this answer.
Set 4: Combine caches, factories, and binding10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
What happens at the final line?
max = 12
result = max([3, 9])
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What does kind(True) return?
from functools import singledispatch
@singledispatch
def kind(value):
return "other"
@kind.register(int)
def _(value):
return "number"
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Why does this method call fail before area runs?
def positive(func):
def wrapper(*args, **kwargs):
for value in args:
if value <= 0:
raise ValueError("positive values required")
return func(*args, **kwargs)
return wrapper
class Panel:
@positive
def area(self, width, height):
return width * height
Panel().area(2, 7)
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
What is the result of render("ok", mode="brief")?
def render(text, *parts, mode, end="."):
return text, parts, mode, end
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
What order does this produce?
rows = [("Zed", 8), ("Ari", 8), ("Bo", 5)]
result = sorted(rows, key=lambda row: (-row[1], row[0]))
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Starting from an empty cache, what are its hits and misses after this sequence?
from functools import lru_cache
@lru_cache(maxsize=2)
def square(n):
return n * n
for n in (4, 7, 4, 9, 7, 9):
square(n)
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What does relay(3, factor=4) return?
def scale(value, /, *, factor=2, **meta):
return value * factor, meta
def relay(*args, **kwargs):
options = {**kwargs, "value": 99}
return scale(*args, **options)
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
What is the value of token()?
def add_left(func):
def wrapper():
return "L" + func()
return wrapper
def add_right(func):
def wrapper():
return func() + "R"
return wrapper
@add_left
@add_right
@add_left
def token():
return "x"
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What values do a, b, and c hold?
from functools import cache
rate = 2
@cache
def cost(n):
return n * rate
a = cost(5)
rate = 3
b = cost(5)
cost.cache_clear()
c = cost(5)
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
What is the final ordering?
def by_distance(target):
return lambda n: abs(n - target)
key = by_distance(8)
result = sorted([12, 7, 9, 4], key=key)
Show answerHide answer
Save this lesson to see this answer.
Set 5: Analyze interacting function patterns10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
key receive in sorted(words, key=...) when the goal is to compare word lengths?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What is the result?
values = [0, 3, 4, 0, 7]
result = list(map(lambda n: n * 2, filter(None, values)))
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
What does the final call return?
from functools import cache
@cache
def make_values(n):
return [n]
first = make_values(4)
first.append(8)
result = make_values(4)
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
After change = build(), what does change() return, and what is the final module value?
value = 40
def build():
value = 3
def change():
nonlocal value
value += 2
def update_module():
global value
value += 5
return value
return value, update_module()
return change
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
What does this reduction return?
from functools import reduce
def collect(acc, word):
longest, total = acc
chosen = word if len(word) > len(longest) else longest
return chosen, total + len(word)
result = reduce(collect, ["elm", "oak", "cedar"], ("", 0))
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What is the result of show(4, *[5, 6], scale=2, x=9)?
def show(x, /, y=1, *rest, scale, **meta):
return x, y, rest, scale, meta
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What is the value of result?
from functools import reduce
def merge(left, right):
return {**left, **right}
result = reduce(merge, [{"x": 1}, {"y": 2}, {"x": 7}], {})
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
What pair of lists is returned by results()?
def results():
live = []
fixed = []
for step in (2, 5, 9):
live.append(lambda n: n + step)
fixed.append(lambda n, step=step: n + step)
return [f(1) for f in live], [f(1) for f in fixed]
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What are a() and then b() after this setup?
def make_counter_decorator():
calls = 0
def decorate(func):
def wrapper():
nonlocal calls
calls += 1
return calls, func()
return wrapper
return decorate
shared = make_counter_decorator()
@shared
def a():
return "a"
@shared
def b():
return "b"
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
What is result?
from functools import partial
import operator
def build():
funcs = []
for offset in (3, 8):
funcs.append(partial(operator.add, offset))
offset = 100
return funcs
result = [f(2) for f in build()]
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accumulator
Argument
"Ari" fills the first ordinary parameter in the call reserve("Ari", seats=4).Argument binding
send(1, value=2) if the first positional parameter is also named value.Argument forwarding
args and kwargs into the target.timeout=3 as a keyword when the target is called.C
Cache hit
Cache miss
Call counter
Call logging
Callable
len, not the string "len" or the result of a call.Callback
key=len lets sorting ask for each word’s length while retaining the original words.Closure
make_multiplier(3) can multiply later inputs by its captured factor of three.Closure cell
__closure__ can show the current factor remembered by a multiplier.Comparison function
functools.cmp_to_key for sorted.D
Decoration time
Decorator
Decorator factory
repeat(3) builds the decorator used by the expression @repeat(3).Decorator stack
Default value
2 fills seats when a booking function is called with only the guest’s name.Dispatch registry
object.Dispatch table
"*" to operator.mul, then call the retrieved function on two numbers.E
Elapsed time
perf_counter differences.F
Fallback implementation
describe handles a string when only integer and list cases have been registered.First-class function
"export" in a dictionary of report operations.Free variable
factor is read by multiply(n) even though only n is its local parameter.Function factory
sorted.Function metadata
wraps makes a wrapper report the original function’s name to inspection tools.G
Generic function
describe can format lists and integers differently while keeping one public call name.Global declaration
count lets count += 1 update the module counter from inside a function.H
Hashable
Higher-order function
I
Initial value
1 makes a product reduction over an empty iterable return the multiplicative identity.K
Key function
len orders names by length without replacing the names with their character counts.Keyword collision
f(1, x=2) fail when x is the first positional-or-keyword parameter.Keyword-only parameter
* or *args and must be supplied by name whenever a caller passes it.strict makes parse(text, strict=True) clearer than a positional flag.L
Lambda expression
lambda row: row[1] reads the second field of each row supplied by sorting.Late binding
step unless each callback receives a separate setting.Lazy iterator
map applies its function as the loop or list requests each result.LEGB
prefix before the module’s prefix when an inner function reads that name.Local binding
LRU eviction
M
Memoization
Mutable default
N
Namespace
LIMIT and a function read, each bound to its object.Nonlocal declaration
total lets an inner accumulator update the total kept by its factory.O
Outermost wrapper
P
Parameter
seats of a reserve function receives 4 when a caller writes reserve("Ari", seats=4).Partial application
partial(round, ndigits=1) builds a one-input rounding operation for map.Per-decoration state
Positional-only parameter
/ in a signature and must receive its value through a positional argument.area(3, 4) but rejects width=3 when width precedes /.Positional-or-keyword parameter
size can be filled by draw(4) or draw(size=4) when it comes first.Predicate
lambda n: n > 0 lets filter keep positive readings and reject zero or negative readings.R
Rebinding
items = items + [x], while items.append(x) changes the list without assigning to items.Reduction
Registration decorator
Retry policy
ConnectionError lets an unrelated ValueError escape without another attempt.Running average
S
Scope
Shadowing
sum with an integer makes a later sum(values) call try to call that integer.Shared mutable state
Signature
(data, /, *, strict=False) makes the data positional and the strict option named.Single dispatch
singledispatch uses the first positional argument’s type.Stable sort
Stateful closure
Stored keyword
base=2 in a parser can be replaced by base=16 on a particular later call.T
Tuple key
(-score, name) puts higher scores first and uses ascending names to break score ties.Type registration
bool can specialize behavior that previously came from an int implementation.U
Unbounded cache
UnboundLocalError
count += 1 when no local count was assigned and no declaration applies.Unpacking
* or a mapping into keyword arguments with **.dist(**point) supplies the x and y values stored under those dictionary keys.V
Validation wrapper
Var-keyword parameter
**details collects city="Lima" when no explicit city parameter exists.Var-positional parameter
*readings allows average(12, 18, 21) to collect three input values.W
Wrapper
*args, **kwargs to preserve the original arguments and returns the result to its caller.wraps
__wrapped__.wraps(func) above a wrapper keeps the public function’s docstring available through help.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.