Python Functions and Decorators

Advanced Functions and Decorators in Python

Go beyond basic functions in Python. Treat functions as values that you can store, pass and return, and use them with 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

  1. Treat functions as objects that can be named, stored, passed and returned, and use higher-order functions such as sorted, map and filter with key functions and lambdas.
    • Treat functions as objects
      Assign 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 lambdas
      Sort and pick items with key functions, write short lambda expressions, and transform or select data with map, filter or a comprehension.
  2. 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 parameters
      Explain 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 arguments
      Collect extra arguments with *args and **kwargs, unpack sequences and dictionaries into a call, and pass arguments unchanged to another function.
    • Require keyword-only and positional-only arguments
      Use * and / in a signature to decide which arguments must be named and which must be given by position, and read a complete signature.
  3. Predict which variable a name refers to with the LEGB rule, and change variables of an outer scope on purpose with global and nonlocal.
    • Find which variable a name refers to
      Use the LEGB rule to resolve names, explain when a name is local, and avoid shadowing and UnboundLocalError.
    • Rebind outer variables with global and nonlocal
      Use global and nonlocal to assign to a variable of the module or of an enclosing function, and know when neither is needed.
  4. 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 variables
      Create 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 binding
      Write closures that remember data between calls, use nonlocal to update it, and fix closures created in loops that all see the last value.
  5. 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.wraps
      Explain the @ syntax, write a wrapper that passes on any arguments and the return value, and keep the original function's metadata with functools.wraps.
    • Give decorators arguments and stack them
      Write decorator factories that take settings, decide the order of stacked decorators, and avoid the missing-parentheses mistake.
    • Use decorators for everyday tasks
      Apply decorators for timing, logging, counting, registration, validation and retrying, on functions and methods, and judge when a decorator helps.
  6. Speed up repeated calls with caching, fix arguments in advance with partial, combine a sequence into one value with reduce, and choose an implementation by type with singledispatch.
    • Cache results with lru_cache and cache
      Memoize functions with functools.lru_cache and functools.cache, read the cache statistics, and know which functions are safe to cache.
    • Fix arguments with partial and combine values with reduce
      Create specialized functions with functools.partial, fold a sequence into one value with functools.reduce, and choose a built-in instead when one exists.
    • Choose behavior by type with singledispatch
      Turn a function into a generic function with functools.singledispatch, register implementations for different types, and predict which one runs.

Python Functions and Decorators study guide

6 chapters

1

Use 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 def for a named or multi-step operation.
  • map transforms items; filter keeps items that pass a truth test.
  • Both map and filter return lazy, exhaustible iterators.
  • reverse=True reverses the complete key ordering, including tie-breakers.
2

Design 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
CallBinding 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 None and create a mutable default inside the body when calls need fresh state.
  • inspect.signature shows 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:

ZoneBinding in this call
Before /: positional-onlya=1
Between / and *args: positional or keywordb=2
Extra positionalsargs=(3, 4)
Named parameters after *argsc=5, d=0
Remaining keywordskwargs={'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 *args makes 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.
3

Apply 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.

ChoiceWhere assignment goesExisting binding required?
No declarationCurrent function's local nameNo
global nameDefining module's namespaceNo
nonlocal nameNearest enclosing function bindingYes

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

  • global directs a function’s binding to its module.
  • nonlocal selects 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.
4

Write 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 with 1; 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 own step.
  • partial(operator.add, step) from functools, 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 partial can 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.
5

Write 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

  • @decorate rebinds a function name to decorate(original).
  • Return the wrapper object during decoration and the desired result during each call.
  • Forward with *args, **kwargs so supported call shapes reach the original.
  • The decorator runs at definition time; its wrapper runs at call time.
  • wraps preserves 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 bottomWhat a cache hit reaches
@timed, @lru_cache()Timing wrapper, then cache
@lru_cache(), @timedCache 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_counter readings.
  • 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.
6

Use 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.
  • partial stores argument objects without copying them.
  • reduce feeds 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

  • singledispatch chooses 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

6 Walkthroughs

1

Pass an operation, then use its results

12 steps
Trace function objects through callbacks, sorting keys, and lazy transformations.
  1. 1
    IntroductionChoose 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?

  2. 2
    ExampleCreate another name for one function
    def add_three(n):
        return n + 3
    
    adjust = add_three
    

    The definition creates a function; the assignment binds adjust to that same object. No addition has happened yet. adjust(4) later returns 7, and adjust.__name__ is still 'add_three'. The object's recorded name does not change each time another variable points to it.

  3. 3
    ExplanationLet 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 to 4, producing 7; the outer call adds three again, producing 10. twice is a higher-order function because it accepts a function. Its call sequence stays the same when the caller chooses a different operation.

  4. 4
    ChallengePass 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 integer 7. Inside twice, Python tries to call that integer as func, raising TypeError. Pass add_three itself so the helper receives behavior it can call on its own input.

  5. 5
    ConnectionStore 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.

  6. 6
    ExampleCompute keys without replacing the items
    words = ["peach", "fig", "plum", "grape"]
    ordered = sorted(words, key=len)
    

    The keys are 5, 3, 4, and 5. Sorting compares those lengths but returns the words: ['fig', 'plum', 'peach', 'grape']. The equal-length pair keeps its input order because sorting is stable. sorted creates a new list; the original words stays in its existing order.

  7. 7
    ExplanationGive 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 explicit return is written inside it.

  8. 8
    ChallengeKeep the tie-breaker in the right direction

    A key is (score, name) and the call uses reverse=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.

  9. 9
    ExampleConsume 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, map takes one value from each per call and stops when the shortest input ends.

  10. 10
    ExplanationKeep items that pass a test

    filter retains original values whose test result is truthy. list(filter(lambda n: n > 0, [-2, 0, 5])) gives [5]. With None as 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.

  11. 11
    ChallengeCombine 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 calls len on each remaining word. Each callback receives the output of the preceding stage, and the final list consumes the lazy results.

  12. 12
    RecapTrace 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.

2

Read and test a complete signature

13 steps
Bind calls, diagnose default sharing, and forward arguments without changing their roles.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionCheck the call before the body
  2. 2
    ExampleFill parameters from the call
  3. 3
    ChallengeFind the duplicate value
  4. 4
    ExampleNotice the shared default object
  5. 5
    TipCreate fresh state inside the call
  6. 6
    ExampleCollect the extra positionals
  7. 7
    ExplanationReverse the stars when making a call
  8. 8
    ChallengeRepair a forwarding helper
  9. 9
    Key InsightA merge and a call handle duplicates differently
  10. 10
    ExplanationRequire named options
  11. 11
    ExampleRead all signature zones
  12. 12
    ChallengeUse a name independently as metadata
  13. 13
    RecapTreat the signature as a binding map
3

Locate the binding before changing it

10 steps
Follow LEGB and choose between mutation, local assignment, global, and nonlocal.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFind the name’s home
  2. 2
    ExplanationSearch in LEGB order
  3. 3
    ExampleAssignment changes the whole function’s lookup
  4. 4
    ChallengeA list update with no declaration
  5. 5
    TipDo not hide the built-in you need
  6. 6
    ExampleRebind a module value explicitly
  7. 7
    ExplanationUpdate the nearest enclosing function
  8. 8
    ChallengeChoose the target of an update
  9. 9
    ChallengeSeparate a block from a scope
  10. 10
    RecapName lookup and object changes are separate
4

Build functions that remember

12 steps
Trace independent factory settings, persistent state, and loop-created callbacks.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionReturn a function with settings attached
  2. 2
    ExampleCreate the factory
  3. 3
    ExampleMake two separate settings
  4. 4
    Key InsightCaptured variables can change
  5. 5
    ChallengeInspect the captured setting
  6. 6
    ExampleCreate a persistent numeric total
  7. 7
    ConnectionKeep only the state the result needs
  8. 8
    ChallengeDistinguish an alias from another factory call
  9. 9
    ExampleBuild callbacks in a loop
  10. 10
    TipBind the intended setting while building
  11. 11
    ChallengeCapture a list shared with the caller
  12. 12
    RecapTrack bindings and shared objects
5

Build and trace reusable decorators

16 steps
Write a wrapper, add a factory layer, stack behaviors, and handle practical call policies.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAdd behavior around the same task
  2. 2
    ExplanationExpand the decoration
  3. 3
    ExampleWrite the forwarding layer
  4. 4
    ExampleSeparate setup from calls
  5. 5
    ChallengeLocate the missing return
  6. 6
    TipPreserve metadata deliberately
  7. 7
    ExampleAdd the settings layer
  8. 8
    ChallengeCall the factory at the right time
  9. 9
    ExplanationTrace a stack from the inside out
  10. 10
    Key InsightLet order express the policy
  11. 11
    ExampleTime successful work
  12. 12
    ConnectionRegister without a wrapper
  13. 13
    ChallengeLeave the method receiver out of a numeric check
  14. 14
    ExplanationRetry only the failures you intend
  15. 15
    ChallengeCombine a counter and a cache
  16. 16
    RecapCheck every layer’s job
6

Choose and trace functools helpers

15 steps
Follow cache entries, prefilled arguments, folds, and type-based implementation selection.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMatch the helper to the job
  2. 2
    ExampleWatch hits and misses
  3. 3
    ChallengeChoose the entry to evict
  4. 4
    ExplanationReuse subproblems in recursion
  5. 5
    Key InsightA cached value can remain shared
  6. 6
    ExampleStore a keyword for future calls
  7. 7
    ChallengeExpand the partial before binding
  8. 8
    ExampleFollow a left fold
  9. 9
    ExplanationStart with the right accumulator
  10. 10
    ExampleCreate a generic function
  11. 11
    ExplanationUse a specific case or a parent
  12. 12
    ChallengeIdentify the dispatching argument
  13. 13
    ChallengeSpot the missing input in a cache key
  14. 14
    ConnectionSeveral helpers still obey ordinary binding
  15. 15
    RecapChoose a helper by its contract

Python Functions and Decorators practice questions

50 Practice Questions in 5 sets

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
  1. 11
  2. 4
  3. None
  4. 7
Show answerHide answer
Answer: A
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
  1. return add(0)
  2. return add
  3. return amount
  4. return add(amount)
Show answerHide answer
Answer: B
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()
  1. "read"
  2. "module"
  3. None
  4. "factory"
Show answerHide answer
Answer: D
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
  1. It returns 11 and leaves the module value at 10.
  2. It raises UnboundLocalError at the first body line.
  3. It returns 7 and leaves the module value at 6.
  4. It returns 7 and changes the module value to 10.
Show answerHide answer
Answer: B
Assignment to 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

Why does show(value=6) fail when show is a singledispatch generic function whose base definition is def show(value)?
  1. The name value must be changed in the base definition.
  2. Integer types cannot use the fallback implementation.
  3. Dispatch requires at least one positional argument.
  4. The base function must have a return annotation.
Show answerHide answer
Answer: C
The dispatch wrapper selects an implementation from the first positional argument. A keyword-only call supplies no such value, so selection fails even though the base signature uses the name 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
  1. inspect_data(data=[3], strict=True)
  2. inspect_data([3], True)
  3. inspect_data([3], 5, True)
  4. inspect_data([3], strict=True)
Show answerHide answer
Answer: D
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()
  1. 1, 2, 3
  2. 1, 1, 1
  3. 1, 2, 1
  4. 2, 2, 1
Show answerHide answer
Answer: C
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")
  1. (7, (8, 9), {"unit": "s"})
  2. (7, [8, 9], {"unit": "s"})
  3. (7, (8, 9, "s"), {})
  4. ([7, 8, 9], (), {"unit": "s"})
Show answerHide answer
Answer: A
The star in the call spreads the list into three positional arguments. 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")
  1. a=["sun", "rain"], b=["sun", "rain"]
  2. a=["sun"], b=["sun", "rain"]
  3. a=["rain"], b=["rain"]
  4. a=["sun"], b=["rain"]
Show answerHide answer
Answer: D
Both calls omit 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)
  1. a=2, b=2; one item.
  2. a=1, b=1; one item.
  3. a=2, b=2; two items.
  4. a=2, b=3; three items.
Show answerHide answer
Answer: C
The first attempt appends and fails; the second appends again and returns 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
  1. name="Noor", seats=True, quiet=False
  2. name="Noor", seats=2, quiet=False
  3. name="Noor", seats=2, quiet=True
  4. name="Noor", seats=None, quiet=True
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
  1. None
  2. It raises TypeError.
  3. 12
  4. 6
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"
  1. Name "wrapper"; the transformed uppercase text.
  2. Name "wrapper"; the original lowercase text.
  3. Name "label"; the transformed uppercase text.
  4. Name "label"; the original lowercase text.
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
  1. global count
  2. nonlocal count
  3. No declaration is needed.
  4. nonlocal 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")
  1. ["oak", "pine"]
  2. []
  3. ["oak"]
  4. ["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()
  1. 3
  2. It raises NameError.
  3. 8
  4. None
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)
  1. a=[6, 9], b=[6, 9]
  2. a=[], b=[6, 9]
  3. a=[2, 5], b=[]
  4. a=[6, 9], b=[]
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A cached function computes a value from a tuple argument. What happens for compute(([1, 2],)), before its body can run?
  1. It computes without caching because the tuple is mutable.
  2. It raises TypeError because the tuple contains an unhashable list.
  3. It caches normally because the outer object is a tuple.
  4. It copies the inner list and caches the copied tuple.
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)
  1. ("integer", "boolean")
  2. ("boolean", "integer")
  3. ("boolean", "boolean")
  4. ("integer", "integer")
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A retry wrapper allows three attempts, catches only 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?
  1. It raises ConnectionError after three attempts.
  2. It raises ValueError after three attempts.
  3. It returns None after the second attempt.
  4. It raises ValueError after two attempts.
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)
  1. ["Ivo", "Mina", "Bo", "Sara"]
  2. [2, 3, 4, 4]
  3. ["Bo", "Ivo", "Sara", "Mina"]
  4. ["Bo", "Ivo", "Mina", "Sara"]
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
  1. "alias"
  2. "finish"
  3. "function"
  4. "value"
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)
  1. 1, with items now containing "r".
  2. It raises UnboundLocalError before appending.
  3. It raises SyntaxError for missing global.
  4. 1, with the module list still empty.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does reduce(operator.sub, [20, 4, 3], 2) return? Assume both names have been imported.
  1. 19
  2. -15
  3. -25
  4. 13
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)
  1. 17
  2. 21
  3. It raises TypeError.
  4. 29
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)
  1. It gives left two values during binding.
  2. It leaves the required right parameter empty.
  3. It rejects the keyword before entering relay.
  4. It passes a tuple and a dictionary to addition.
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)
  1. 20.0
  2. 15.0
  3. 18.0
  4. 24.0
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()
  1. ["enter", "setup", "body", "exit", "enter", "setup", "body", "exit"]
  2. ["setup", "body", "enter", "exit", "body", "enter", "exit"]
  3. ["setup", "enter", "body", "exit", "enter", "body", "exit"]
  4. ["setup", "enter", "body", "exit", "setup", "enter", "body", "exit"]
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")
  1. It returns "x-y" and ignores the new keyword.
  2. It raises TypeError because b gets two values.
  3. It returns "y-z" because the new positionals win.
  4. It returns "x-z" because the keyword wins.
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)
  1. [2, 3]
  2. [2, 2, 3]
  3. []
  4. [2]
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])
  1. It raises TypeError because an integer is called.
  2. It raises NameError because max was replaced.
  3. It returns 12, the value bound to max.
  4. It returns 9, the largest list item.
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"
  1. "bool"
  2. "other"
  3. "number"
  4. It raises TypeError.
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)
  1. The decorator runs only after the method returns.
  2. The wrapper drops both measurement arguments.
  3. The measurements bind to the same parameter.
  4. The validator compares the Panel instance with zero.
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
  1. ("ok", ("brief",), None, ".")
  2. ("ok", (), "brief", ".")
  3. ("ok", (), "brief", None)
  4. It raises TypeError because mode has no default.
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]))
  1. [("Bo", 5), ("Ari", 8), ("Zed", 8)]
  2. [("Zed", 8), ("Ari", 8), ("Bo", 5)]
  3. [("Bo", 5), ("Zed", 8), ("Ari", 8)]
  4. [("Ari", 8), ("Zed", 8), ("Bo", 5)]
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)
  1. 2 hits and 4 misses.
  2. 1 hit and 5 misses.
  3. 0 hits and 6 misses.
  4. 3 hits and 3 misses.
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)
  1. (396, {})
  2. (6, {"factor": 4, "value": 99})
  3. (12, {"value": 99})
  4. It raises TypeError for duplicate value.
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"
  1. "LxRL"
  2. "LLxR"
  3. "LRLx"
  4. "LxRR"
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)
  1. 15, 15, 15
  2. 10, 10, 10
  3. 10, 15, 15
  4. 10, 10, 15
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)
  1. [1, 1, 4, 4]
  2. [4, 7, 9, 12]
  3. [7, 9, 12, 4]
  4. [7, 9, 4, 12]
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

What must key receive in sorted(words, key=...) when the goal is to compare word lengths?
  1. "len"
  2. len
  3. len(words)
  4. list(words)
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)))
  1. [8]
  2. [0, 6, 8, 0, 14]
  3. [6, 8, 14]
  4. [3, 4, 7]
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)
  1. [4]
  2. [8]
  3. It raises TypeError.
  4. [4, 8]
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
  1. The call returns (5, 45); the module value is 45.
  2. The call returns (5, 10); the module value is 40.
  3. The call returns (5, 45); the module value is 40.
  4. The call returns (42, 47); the module value is 47.
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))
  1. ("cedar", 5)
  2. ("cedar", 8)
  3. ("cedar", 11)
  4. ("oak", 11)
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
  1. (9, 5, (6,), 2, {})
  2. (4, 5, (6,), 2, {"x": 9})
  3. A TypeError for duplicate x values.
  4. (4, 1, (5, 6), 2, {"x": 9})
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}], {})
  1. [{"x": 1}, {"y": 2}, {"x": 7}]
  2. {"x": 1, "y": 2}
  3. {"x": [1, 7], "y": 2}
  4. {"x": 7, "y": 2}
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]
  1. ([10, 10, 10], [3, 6, 10])
  2. ([10, 10, 10], [10, 10, 10])
  3. ([3, 6, 10], [10, 10, 10])
  4. ([3, 6, 10], [3, 6, 10])
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"
  1. (0, "a") then (1, "b")
  2. (2, "a") then (2, "b")
  3. (1, "a") then (2, "b")
  4. (1, "a") then (1, "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()]
  1. [3, 8]
  2. [5, 10]
  3. [102, 102]
  4. [10, 10]
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

74 Key Terms, each with its definition

A

Accumulator
An accumulator is the running result passed as the first argument to the combining function during a left-to-right reduction.
An accumulator starting at zero can collect the lengths of several words into one integer total.
Argument
An argument is a value supplied in a function call, either by position, by a keyword name, or through unpacking.
The argument "Ari" fills the first ordinary parameter in the call reserve("Ari", seats=4).
Argument binding
Argument binding is the process of matching a call’s positional and keyword values to a function’s parameters before its body runs.
Argument binding rejects send(1, value=2) if the first positional parameter is also named value.
Argument forwarding
Argument forwarding passes a collected call to another callable, usually by unpacking args and kwargs into the target.
Argument forwarding in a wrapper preserves timeout=3 as a keyword when the target is called.

C

Cache hit
A cache hit occurs when a call finds a stored result for its key, allowing the wrapper to return it without entering the original body.
A cache hit skips a print inside the original function as well as skipping that function’s calculation.
Cache miss
A cache miss occurs when a call has no stored entry for its key and must run the original function to obtain a result.
A cache miss can occur for a repeated input if its earlier result has already been evicted.
Call counter
A call counter is state incremented when a wrapper is entered, often exposed as an attribute on the decorated callable.
A call counter incremented before the original call includes attempts whose original function later raises.
Call logging
Call logging records information about function invocations, such as selected arguments or results, while the wrapped work is performed.
Call logging can display a function’s name before forwarding a call and show its result after success.
Callable
A callable is an object that can be invoked with parentheses, including functions, methods, classes, and suitable instances.
A callback parameter needs a callable such as len, not the string "len" or the result of a call.
Callback
A callback is a callable passed to other code so that code can invoke it when it needs the supplied behavior.
The callback passed as key=len lets sorting ask for each word’s length while retaining the original words.
Closure
A closure is an inner function together with the enclosing variables it uses, keeping those variables accessible after the outer call ends.
A closure returned by make_multiplier(3) can multiply later inputs by its captured factor of three.
Closure cell
A closure cell holds a captured binding so that functions sharing the variable can keep accessing it after the enclosing call returns.
A closure cell inspected through __closure__ can show the current factor remembered by a multiplier.
Comparison function
A comparison function takes two items and returns a negative, zero, or positive value to describe their relative order.
A comparison function from older sorting code can be adapted with functools.cmp_to_key for sorted.

D

Decoration time
Decoration time is when a decorated definition executes and its decorators are applied to determine the resulting bound object.
Decoration time is when a registration decorator adds a newly defined handler to the registry.
Decorator
A decorator takes a function and returns the object that the function’s name will refer to after the decorated definition executes.
A decorator can replace a reporting function with a wrapper that records its calls and returns its result.
Decorator factory
A decorator factory accepts settings and returns a decorator, which can then receive a function and construct its configured wrapper.
A decorator factory called as repeat(3) builds the decorator used by the expression @repeat(3).
Decorator stack
A decorator stack applies several decorators to one definition, with the bottom decorator applied first and the top result bound last.
A decorator stack with timing above caching measures calls that hit as well as calls that miss.
Default value
A default value is an object evaluated when a definition executes and used when a caller omits the corresponding argument.
The default value 2 fills seats when a booking function is called with only the guest’s name.
Dispatch registry
A dispatch registry maps registered types to implementations and includes the base function registered for object.
The dispatch registry can be inspected to see which type-specific implementations a generic function currently supports.
Dispatch table
A dispatch table is a mapping from selection keys to callables, allowing a lookup to choose the operation to run.
A dispatch table can map "*" to operator.mul, then call the retrieved function on two numbers.

E

Elapsed time
Elapsed time is the duration between two readings of an appropriate clock, measured in seconds by perf_counter differences.
Elapsed time printed after a successful function call can show how long that wrapped operation took.

F

Fallback implementation
A fallback implementation handles values when no more specific registered implementation applies; it is the decorated base function.
The fallback implementation of a generic function describe handles a string when only integer and list cases have been registered.
First-class function
A first-class function is a function that can be assigned, stored, passed, and returned as a value in a program.
A first-class function can be stored under the key "export" in a dictionary of report operations.
Free variable
A free variable of an inner function is a variable that it uses from an enclosing function instead of binding it locally.
The free variable factor is read by multiply(n) even though only n is its local parameter.
Function factory
A function factory creates and returns callables, often using closures to attach settings or state from each factory call.
A function factory can return a distance key configured for a target, ready to pass to sorted.
Function metadata
Function metadata is descriptive information stored on a function, including its name, docstring, module, and annotations.
Function metadata copied by wraps makes a wrapper report the original function’s name to inspection tools.

G

Generic function
A generic function offers one callable name with several implementations, selecting an implementation according to a dispatch rule.
A generic function named describe can format lists and integers differently while keeping one public call name.
Global declaration
A global declaration directs a function’s uses of a named variable to the defining module’s namespace, including assignments.
A global declaration for count lets count += 1 update the module counter from inside a function.

H

Hashable
An object is hashable when it has a stable hash value during its lifetime and supports equality consistent with dictionary-key use.
A hashable tuple can serve as a cache argument, but a tuple containing a list cannot be used that way.
Higher-order function
A higher-order function accepts another function as an argument, returns a function, or does both in its operation.
A higher-order function can apply a supplied adjustment twice without knowing how that adjustment works.

I

Initial value
An initial value starts a reduction before its items and supplies the result when the iterable contains no items.
An initial value of 1 makes a product reduction over an empty iterable return the multiplicative identity.

K

Key function
A key function computes a comparison value for an item while sorting or selection still returns the original item.
The key function len orders names by length without replacing the names with their character counts.
Keyword collision
A keyword collision occurs when a call supplies the same keyword twice or also supplies a positional value for its ordinary parameter.
A keyword collision makes f(1, x=2) fail when x is the first positional-or-keyword parameter.
Keyword-only parameter
A keyword-only parameter follows a bare * or *args and must be supplied by name whenever a caller passes it.
The keyword-only parameter strict makes parse(text, strict=True) clearer than a positional flag.

L

Lambda expression
A lambda expression creates a function whose body is a single expression and whose return value is that expression’s result.
The lambda expression lambda row: row[1] reads the second field of each row supplied by sorting.
Late binding
Late binding means a function reads a referenced variable when called, so loop-created closures can all see the loop’s final value.
Late binding makes three callbacks read the same final step unless each callback receives a separate setting.
Lazy iterator
A lazy iterator produces its results when consumed instead of computing and storing all of them when it is created.
A lazy iterator returned by map applies its function as the loop or list requests each result.
LEGB
LEGB names the ordinary function lookup order: local, enclosing functions, global module scope, and then built-ins.
LEGB finds the factory’s prefix before the module’s prefix when an inner function reads that name.
Local binding
A local binding associates a name with an object in the current function, unless a declaration directs that name elsewhere.
A local binding introduced by assignment makes earlier uses of that name local in the same function.
LRU eviction
LRU eviction removes the least recently used entry when a bounded cache needs space for a new call result.
LRU eviction preserves a recently accessed entry even if it was originally inserted before another entry.

M

Memoization
Memoization stores results under their call arguments so repeated calls can reuse an earlier result without executing the original computation.
Memoization prevents a recursive Fibonacci function from recomputing the same input throughout its call tree.
Mutable default
A mutable default is a default object that can be changed in place, allowing changes to persist across calls that reuse it.
A mutable default list keeps earlier tags unless the function creates a fresh list inside each relevant call.

N

Namespace
A namespace is a mapping from names to objects, such as the names defined in a module or in a function’s local environment.
The module namespace can contain both a constant LIMIT and a function read, each bound to its object.
Nonlocal declaration
A nonlocal declaration directs a name to the nearest existing binding in an enclosing function, allowing that binding to be reassigned.
A nonlocal declaration for total lets an inner accumulator update the total kept by its factory.

O

Outermost wrapper
The outermost wrapper is the callable entered first in a wrapped call chain and the last layer through which a normal result returns.
An outermost wrapper for access checks can run before an inner cache decides whether to reuse a result.

P

Parameter
A parameter is a named input in a function definition that receives a value when arguments are bound during a call.
The parameter seats of a reserve function receives 4 when a caller writes reserve("Ari", seats=4).
Partial application
Partial application creates a callable with some arguments already supplied, leaving the remaining values for later calls.
Partial application with partial(round, ndigits=1) builds a one-input rounding operation for map.
Per-decoration state
Per-decoration state is data created separately for each application of a decorator, usually shared only by that decoration’s calls.
Per-decoration state lets two independently decorated functions keep separate call counters.
Positional-only parameter
A positional-only parameter appears before / in a signature and must receive its value through a positional argument.
A positional-only parameter allows area(3, 4) but rejects width=3 when width precedes /.
Positional-or-keyword parameter
A positional-or-keyword parameter accepts either a positional value or a keyword value, but cannot receive both in one call.
A positional-or-keyword parameter size can be filled by draw(4) or draw(size=4) when it comes first.
Predicate
A predicate is a callable used as a test; its truth value determines whether an item meets a condition.
The predicate lambda n: n > 0 lets filter keep positive readings and reject zero or negative readings.

R

Rebinding
Rebinding changes which object a name refers to; it differs from changing the contents of an object reached through that name.
Rebinding occurs in items = items + [x], while items.append(x) changes the list without assigning to items.
Reduction
A reduction combines a sequence into one result by repeatedly calling a two-argument function with an accumulator and the next item.
A reduction with subtraction must preserve left-to-right grouping because changing the grouping changes the result.
Registration decorator
A registration decorator stores a function in a lookup structure during decoration, often returning the original function unchanged.
A registration decorator makes an export handler available by name without adding a per-call wrapper.
Retry policy
A retry policy specifies which failures can trigger another attempt and the maximum number of attempts the wrapper will allow.
A retry policy limited to ConnectionError lets an unrelated ValueError escape without another attempt.
Running average
A running average is the mean of the values seen so far, updated for each new value using stored readings or a total and count.
A running average can process temperature readings while storing only two numbers instead of a growing list.

S

Scope
A scope determines where a name can be used and which binding Python selects when that name appears in code.
A function’s local scope takes priority over a same-named module variable when that local has a value.
Shadowing
Shadowing occurs when a nearer binding hides a same-named binding that lookup would otherwise find in an outer scope.
Shadowing the built-in sum with an integer makes a later sum(values) call try to call that integer.
Shared mutable state
Shared mutable state is changeable data reached by more than one reference, so a mutation through one reference is visible through others.
Shared mutable state remains possible when a closure captures a list that the caller also keeps.
Signature
A signature describes a callable’s parameters, their order, their defaults, and the markers that constrain how arguments are passed.
The signature (data, /, *, strict=False) makes the data positional and the strict option named.
Single dispatch
Single dispatch selects an implementation using one argument’s type; singledispatch uses the first positional argument’s type.
Single dispatch ignores the second argument’s type when selecting a two-argument function’s implementation.
Stable sort
A stable sort preserves the original relative order of items whose comparison keys are equal to each other.
A stable sort keeps two equally scored records in their arrival order when score is the only key.
Stateful closure
A stateful closure retains data between calls, allowing each call to read or update information left by earlier calls.
A stateful closure can return consecutive counter values without exposing a module-level counter.
Stored keyword
A stored keyword is a named argument retained in a partial object and used unless a later call supplies that keyword again.
The stored keyword base=2 in a parser can be replaced by base=16 on a particular later call.

T

Tuple key
A tuple key is a comparison key containing several fields, compared in order until a differing field decides the order.
The tuple key (-score, name) puts higher scores first and uses ascending names to break score ties.
Type registration
A type registration associates a type with an implementation in a generic function, using an explicit type or a readable annotation.
A type registration for bool can specialize behavior that previously came from an int implementation.

U

Unbounded cache
An unbounded cache stores entries without a capacity-based eviction limit, retaining distinct call results until cleared or released.
An unbounded cache can keep growing when a long-running program receives many different inputs.
UnboundLocalError
An UnboundLocalError is raised when function code tries to read a name treated as local before that local has a value.
UnboundLocalError can occur at count += 1 when no local count was assigned and no declaration applies.
Unpacking
Unpacking in a call spreads an iterable into positional arguments with * or a mapping into keyword arguments with **.
Unpacking with dist(**point) supplies the x and y values stored under those dictionary keys.

V

Validation wrapper
A validation wrapper checks supplied inputs before invoking the original callable, rejecting values that violate its stated rules.
A validation wrapper for positive measurements must avoid comparing an instance method’s receiver with zero.
Var-keyword parameter
A var-keyword parameter uses two stars in a definition to collect otherwise unmatched keyword arguments into a dictionary.
The var-keyword parameter **details collects city="Lima" when no explicit city parameter exists.
Var-positional parameter
A var-positional parameter uses one star in a definition to collect extra positional arguments into a tuple.
The var-positional parameter *readings allows average(12, 18, 21) to collect three input values.

W

Wrapper
A wrapper is a callable that invokes another callable while adding behavior before, after, or around that invocation.
A wrapper forwards *args, **kwargs to preserve the original arguments and returns the result to its caller.
wraps
The wraps helper decorates a wrapper to preserve the wrapped function’s metadata and link back to it through __wrapped__.
Using wraps(func) above a wrapper keeps the public function’s docstring available through help.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started