smartyfy.mrindigi.com

Python Master Course V2 — 103. Decorators and Function Wrappers

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 11 · LESSON 103 OF 200

Decorators and Function Wrappers

Study: 90–120 minutes · Prerequisites: Lessons 101–102, functions, classes, exceptions and tests.

Course hub · Previous lesson

Video lesson

Video not yet available. A verified video URL/player will be added when supplied.

Learning outcomes

Explain decorators and function wrappers, reason about runtime behavior, apply the technique in a maintainable program, and test normal, boundary and invalid inputs.

Understand and apply: Decorators and Function Wrappers

A decorator receives a callable and returns a callable. functools.wraps preserves metadata and __wrapped__, which helps debugging and introspection.

Closures are introduced here as the wrapper mechanism. For a fuller treatment, see Lesson 105: Closures and Lexical Scope.

A decorator changes which callable a name refers to

Functions are objects: a function can accept another function, retain it, and return a new function. A decorator applies that pattern when a function is defined. Writing @logged above def double is equivalent to defining double and then assigning double = logged(double). Decoration happens once at definition time; the returned wrapper runs on every later call. This distinction matters when configuration or shared state is captured.

The wrapper is a closure: it can still access the original function through an enclosing binding after the decorator has returned. Forward *args and **kwargs so positional and keyword calls work, and return the original result. Without return, an otherwise successful wrapped call produces None. functools.wraps copies useful metadata and exposes __wrapped__ for introspection; it does not automatically forward arguments, preserve behavior or enforce the original signature.

Time both successful and failed calls

A timing decorator separates repeated measurement from application logic. A decorator factory adds configuration: timed(…) first receives a clock and a reporting function, then its returned decorate function receives the target. The default clock is perf_counter, which measures elapsed time. Injecting a deterministic clock makes the wrapper testable without asserting a machine-dependent duration.

Python example

from functools import wraps
from time import perf_counter

def timed(*, clock=perf_counter, report=print):
    def decorate(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            started = clock()
            try:
                return function(*args, **kwargs)
            finally:
                report((function.__name__, clock() - started))
        return wrapper
    return decorate

ticks = iter([1.0, 1.25, 2.0, 2.5])
measurements = []

@timed(clock=lambda: next(ticks), report=measurements.append)
def divide(total, *, parts):
    """Divide a total into equal parts."""
    return total / parts

print(divide(8, parts=2))
try:
    divide(8, parts=0)
except ZeroDivisionError:
    print("failure propagated")
print(divide.__name__)
print(measurements)
assert divide.__wrapped__(8, parts=2) == 4

Expected output

4.0
failure propagated
divide
[('divide', 0.25), ('divide', 0.5)]

On success, the result is evaluated, finally records the duration, and the result reaches the caller. On failure, finally still records the duration, then the original exception propagates. Reporting must itself be reliable: if report raises, its exception can obscure an application failure or replace a successful return. Decide that policy deliberately rather than catching every exception around the entire wrapper. Never include passwords or complete request payloads in timing logs.

Trace stacking from the outside inward

Python example

from functools import wraps

def marked(label):
    def decorate(function):
        @wraps(function)
        def wrapper():
            print(label, "before")
            try:
                return function()
            finally:
                print(label, "after")
        return wrapper
    return decorate

@marked("outer")
@marked("inner")
def work():
    print("body")

work()

Expected output

outer before
inner before
body
inner after
outer after

Stacking means work = marked("outer")(marked("inner")(work)). The outer wrapper enters first and leaves last. Ordering changes meaning: timing outside a retry wrapper measures all attempts, whereas timing inside measures each attempt. Keep wrappers small enough that their order remains understandable. Use a normal helper call when the behavior applies at one explicit location rather than every invocation.

This synchronous timing pattern measures completion only for ordinary synchronous functions. Wrapping a generator function measures creation of its generator, and wrapping an async function measures creation of its coroutine. Measuring their actual work requires a wrapper that consumes or awaits appropriately. Test returned values, keyword forwarding, metadata, exception propagation and one timing event for each attempted call.

Progressive runnable examples

Requires Python 3.10+. Save as lesson103.py and run python lesson103.py or python3 lesson103.py. Expected outputs below are illustrative and not claimed to have been executed on Smartyfy.

Example 1 — Core mechanism

from functools import wraps

def logged(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        print('calling', fn.__name__)
        return fn(*args, **kwargs)
    return wrapper

@logged
def double(n):
    return n * 2
print(double(6))
print(double.__name__)

Expected output:

calling double
12
double

Guided practical project

Project: Build a timing decorator with perf_counter, wraps, and a finally block so failures are still measured.

Use the complete implementation and explicit contract in the worked explanation above. Reproduce its deterministic sample, test the stated boundary and failure cases, and explain the documented limitations before adapting it.

Common mistakes and debugging

  • Adding abstraction without a demonstrated need.
  • Hiding state or unexpected side effects.
  • Assuming type hints replace validation.
  • Ignoring resource cleanup or error propagation.
  • Measuring performance on unrepresentative data.
  • Failing to test boundary and error cases.

Debug by reproducing the smallest failing input, inspecting the traceback and intermediate values, then adding a regression test.

Practice with explained answers

Predict each result before opening the answer. Trace state changes and explain the contract as well as the output.

When does @timed(…) run, and when does its wrapper run?

The factory and decorator run while the function definition is evaluated. They return the replacement callable. The wrapper runs each time that replacement is called, so its start time must be taken inside wrapper, not in the factory.

Why is return function(*args, **kwargs) essential?

It forwards both kinds of arguments and returns the application result. Omitting return lets the wrapper finish with None, changing the decorated function’s contract even if the original computation succeeded.

What does wraps preserve, and what does it not guarantee?

It copies metadata such as name, documentation and annotations and sets __wrapped__. It does not prove argument compatibility, runtime types or behavioral equivalence. Those depend on the wrapper implementation and tests.

What is the exact stacking order in the marked example?

The inner decorator is applied first, but the outer wrapper is called first. Execution is outer before, inner before, body, inner after, outer after. A finally block provides the corresponding exit action when the body raises too.

Why does the failed divide call still have a timing record?

The timing call is in finally, which runs while leaving the protected call. The ZeroDivisionError is then propagated because the wrapper neither catches it nor returns from finally. A return in finally would wrongly suppress it.

Will this decorator measure how long a generator takes to produce all values?

No. Calling a generator function creates a suspended generator quickly. The work runs during later iteration, after this wrapper has finished. Measure consumption at the caller or design a generator-aware wrapper with explicit cleanup and exception semantics.

Mastery checkpoint

Explain the concept without notes, reproduce the core example, finish the project, run three tests and justify when the technique is appropriate. No account-synced completion or certification is claimed.

Course hub · Previous lesson 102 is available through the hub · Next lesson 104 will be linked after publication.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.