Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 29 / ADVANCED LANGUAGE FEATURES

Decorators that preserve contracts

Wrap behaviour without losing metadata, signatures or ownership.

AdvancedTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain a decorator transforms a callable
  • Apply forward explicitly
  • Reason about observe without distorting
01

A decorator transforms a callable

A decorator takes a callable and returns the callable to use in its place. A nested wrapper can remember the original function through a closure.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Add a reusable policy while preserving a meaningful result, instead of pasting the same wrapper logic into every function.

Words you will see

Callable
An object you can call with parentheses, such as a function.
Decorator
A transformation applied to a function after its definition.
Closure
A nested function retaining access to bindings in an enclosing call after that call returns.

Expand the @ spelling

@double_result above score means score = double_result(score) after the original function is created. double_result receives that original function, defines wrapped and returns it. The public name score now points to wrapped.

When score(3) is called, wrapped calls the retained original, which returns 4, then doubles it to 8. The original does not call the wrapper recursively; the enclosed function binding still identifies the original callable.

Keep ownership and return visible

The wrapper has its own return statement. Calling function(value) alone would discard 4 and make the wrapper return None. The closure keeps the original reachable; it is not a frozen copy of every object the function may use.

This small example accepts one positional value only. It teaches substitution, not a general-purpose signature-preserving decorator. Forwarding arbitrary arguments and preserving metadata follow in the next concept.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. def wrapped(value):

    Create a nested function retaining the enclosing function binding.

  2. return 2 * function(value)

    Call the original once and return twice its result.

  3. return wrapped

    Return a callable, without calling it during decoration.

  4. @double_result

    Replace score with the returned wrapper after its definition.

The @decorator spelling is roughly function = decorator(function) after definition. A wrapper can add validation, metrics or a policy check, but callers still need the same meaningful return and exception contract.

Predict before you run

What does score(3) return?

Replace the public callablePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Expose the wrapper's return rule.

Try: Replace return 2 * function(value) with function(value).

The call prints None because the original result is discarded.

Change the original calculation.

Try: Change return value + 1 to return value + 2.

score(3) becomes 10: the wrapper still doubles the original's new result.

Before you move on

After decoration, what is retained by wrapped, and when does the original score body run?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

The closure retains the original function binding. Its body runs when the wrapper is invoked, not merely when the decorator returns the wrapper.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Forward explicitly

A forwarding wrapper must pass arguments and return values explicitly. functools.wraps preserves useful metadata and the wrapped reference, not the body logic.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Let callers keep using named options and readable function names after decoration.

Words you will see

Metadata
Descriptive attributes such as __name__ and __doc__.
__wrapped__
A reference installed by wraps to the wrapped function.
Forwarding
Passing received positional and keyword arguments to another callable.

Pass the call through once

wrapped collects positional arguments and keyword options, expands both into function and returns its result. For greet('Ada', punctuation='?'), the original joins 'Hi ', 'Ada' and '?', so the wrapper returns 'Hi Ada?'.

@wraps(function) copies selected metadata and sets __wrapped__. The public name greet still points to the wrapper, but greet.__name__ reports greet. Without wraps this small wrapper's reported name would be wrapped.

Know what metadata cannot do

wraps does not automatically add a missing return, await a coroutine, validate inputs or copy the original function's executable parameter list. inspect.signature normally follows __wrapped__, which is useful but separate from runtime forwarding.

Exceptions from the original should propagate unless the decorator explicitly documents another policy. This pass-through wrapper does not catch errors or perform I/O. It borrows arguments; any mutation done by the original still follows the original's ownership contract.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. @wraps(function)

    Copy useful metadata from the original onto wrapped.

  2. return function(*args, **kwargs)

    Unpack the complete call and return the original result.

  3. print(greet.__name__)

    Show the preserved original name rather than wrapped.

Use functools.wraps to preserve useful metadata and the wrapped reference. A wrapper that forgets return changes the result to None. Separate decoration-time configuration from work that should happen on every invocation.

Predict before you run

What is the second printed line?

Forward and preserve a namePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Drop a keyword deliberately.

Try: Change the forwarding call to function(*args).

The greeting uses the default ! instead of ?, exposing lost behavior despite preserved metadata.

Inspect the original reference.

Try: Add print(greet.__wrapped__('Lin')).

It prints Hi Lin! by calling the original function directly, bypassing this wrapper.

Before you move on

Would @wraps make a body containing only function(*args, **kwargs) return the original result?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. The wrapper would still return None. Metadata preservation and returned-value preservation are separate responsibilities.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

A parameterised multiplier decorator

A parameterised decorator uses one call to remember configuration, one call to receive a function and later calls to perform the wrapped work.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Reuse one result-scaling policy with different factors while keeping each wrapper's configuration separate.

Words you will see

Decorator factory
A function returning a decorator, such as multiply_result(2).
Captured binding
An enclosing name still accessible to a nested function.
Invocation
A particular call of the returned wrapped function.

Separate the three layers

multiply_result(2) binds factor to 2 and returns decorate. decorate receives the original total function, creates wrapped, applies wraps and returns it. These steps happen when the definition is processed, before total is called.

total([2, 3]) later invokes wrapped. It forwards the list to the original total, gets sum 5, multiplies by captured factor 2 and returns 10. The next print reads the preserved __name__, which is total.

Each factory call owns its binding

Calling multiply_result(3) separately would create a different factor binding. A closure retains bindings, not a deep snapshot: capturing a mutable configuration object would keep a reference to that object.

The arithmetic contract here expects a numeric result that can be multiplied. It is not suitable for every callable, async result or generator stream. It neither measures performance nor adds retries or process isolation.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. def multiply_result(factor):

    Bind configuration in a separate outer call.

  2. def decorate(function):

    Receive the original total after the factory returns a decorator.

  3. return factor * function(*args, **kwargs)

    At invocation, forward the list, calculate 5, then return 10.

  4. print(total.__name__)

    The wraps metadata makes this print total.

The outer function captures configuration; the inner wrapper forwards the call, returns the value and preserves the original name.

Conceptual closure and call layers in the preserved multiplier example; no measured stack or heap layout is implied.

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. Configuremultiply_result(2) → decorate; the enclosing factor binding remains available.
  2. Decoratedecorate(original total) → wrapped; retain the original function and preserve its metadata.
  3. Invoke laterwrapped([2, 3]) → original total([2, 3]) → 5.
  4. Return policycaptured factor 2 * result 5 → return 10; the original runs once.
Predict before you run

How many times does the original total run in total([2, 3])?

A parameterised multiplier decoratorPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Use another configuration.

Try: Change @multiply_result(2) to @multiply_result(3).

The first output becomes 15; the name output is still total.

Test an empty numeric input.

Try: Change [2, 3] to [].

sum returns 0 and multiplication returns 0; decoration itself does not run sum.

Before you move on

With factor 3 and total([1, 2]), when is 9 computed?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

Only when the wrapped total is invoked. Decoration stores factor 3 and the original function; the later invocation computes sum 3 and multiplies it by 3.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

Decorators can apply a cross-cutting policy while keeping a function's domain calculation readable. Validation, tracing or caching are common uses, but every wrapper changes a callable boundary. Decide which return values, exceptions, metadata and invocation styles must remain compatible before introducing one.

Follow the mechanism step by step

At definition time, the decorator receives the function and returns the callable bound to its name. A parameterised decorator first receives configuration and returns that decorator. At call time, the wrapper binds or forwards arguments, executes its policy and invokes the original function. These phases can retain different state and fail at different times.

Work through a concrete application

Trace the multiply-result example from outside inward: factor is captured once, total is supplied during decoration, and values arrive during invocation. functools.wraps preserves useful metadata and the wrapped reference. Ensure the wrapper returns the original or deliberately transformed result instead of accidentally returning None.

Failure cases and misleading shortcuts

Stacked decorators apply from bottom to top. Changing their order can make validation occur after caching or cause metrics to count retries rather than logical operations. A synchronous wrapper around a coroutine can return an unawaited coroutine and miss exceptions raised during its later execution.

Cost, ownership and alternatives

A cache retains arguments and results and needs a freshness/size policy. A retry wrapper needs classification, limits and idempotency awareness. A timing wrapper adds overhead. Avoid choosing a generic decorator when an explicit call makes lifecycle, resource use or authorization easier for reviewers to see.

Verify the contract

Test positional and keyword calls, return values, exceptions and metadata. For an async callable, actually await the decorated function and verify cancellation/cleanup as well as a successful result. Test decorator ordering using an observable event sequence rather than relying on visual intuition about stacked annotations.

Transfer question: Does wraps guarantee that a wrapper forwards every call correctly?

No. It copies useful metadata and exposes the wrapped callable, but the wrapper's body still decides argument forwarding, return behaviour and awaiting. Static typing and runtime contract tests provide additional evidence; neither is replaced by the metadata decorator.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

What happens if a wrapper calls the original function but forgets return?
TRANSFER THE IDEA

Rebuild: A parameterised multiplier decorator

Without copying the worked code, reproduce its observable contract: The outer function captures configuration; the inner wrapper forwards the call, returns the value and preserves the original name. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Create independent configured functions

Build a closure that adds a captured offset.

The contract

  • Implement make_offset(amount) for integer amounts; return a callable accepting one integer value.
  • The callable returns integer value + amount; separate factory calls retain independent amounts.
  • Do not use shared global configuration or mutate inputs. This is a closure factory, not yet @ syntax.
Create independent configured functionsPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. positive offset
    f = make_offset(3); assert callable(f); r = f(4); assert type(r) is int and r == 7
  2. zero offset
    f = make_offset(0); assert callable(f); r = f(5); assert type(r) is int and r == 5
  3. negative offset
    f = make_offset(-4); assert callable(f); r = f(2); assert type(r) is int and r == -2
  4. independence
    a = make_offset(2); b = make_offset(9); assert callable(a) and callable(b); x = a(1); y = b(1); assert type(x) is int and type(y) is int and (x, y) == (3, 10)
  5. repeated calls
    f = make_offset(2); assert callable(f); a = f(3); b = f(3); assert type(a) is int and type(b) is int and (a, b) == (5, 5)
  6. loop factories
    fs = [make_offset(i) for i in range(3)]; assert all(callable(f) for f in fs); r = [f(10) for f in fs]; assert all(type(x) is int for x in r) and r == [10, 11, 12]
    How is this different from late-bound callbacks sharing a loop variable?

    Each factory invocation creates a distinct amount binding. Creating a closure takes O(1) local state; each numeric call does one addition, subject to integer size. Retained objects live as long as their closures need them.

    GUIDED PRACTICE

    Wrap without changing the call

    Create a pass-through decorator that preserves metadata, values and exceptions.

    The contract

    • Implement preserve_call(function); return a synchronous wrapper forwarding all positional and keyword arguments exactly once.
    • Return the original result with its type and identity unchanged; let original exceptions propagate.
    • Use functools.wraps to preserve __name__, __doc__ and __wrapped__. Do not copy/mutate inputs or add retries. Async/generator-specific wrapping is outside scope.
    Wrap without changing the callPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. numeric forwarding
      def f(a, b):
          return a + b
      w = preserve_call(f); assert callable(w); r = w(2, 3); assert type(r) is int and r == 5
    2. keyword option
      def f(name, *, end='!'):
          return name + end
      w = preserve_call(f); assert callable(w); r = w('x', end='?'); assert type(r) is str and r == 'x?'
    3. no arguments
      def f():
          return []
      w = preserve_call(f); assert callable(w); r = w(); assert type(r) is list and r == []
    4. identity and preservation
      p = [3, 1, 3]
      def f(values):
          return values
      w = preserve_call(f); assert callable(w); r = w(p); assert type(r) is list and r is p and r == [3, 1, 3] and p == [3, 1, 3]
    5. metadata
      def f(x):
          'Add one.'
          return x + 1
      w = preserve_call(f); assert callable(w); r = w(3); assert type(r) is int and r == 4 and w.__name__ == 'f' and w.__doc__ == 'Add one.' and w.__wrapped__ is f
    6. once and exception
      calls = []
      def f(x):
          calls.append(x)
          if x < 0:
              raise ValueError('negative')
          return x
      w = preserve_call(f); assert callable(w); r = w(2); assert type(r) is int and r == 2 and calls == [2]
      try:
          w(-1)
      except ValueError as e:
          assert str(e) == 'negative' and calls == [2, -1]
      else:
          raise AssertionError('error swallowed')
      Does wraps preserve executable behavior by itself?

      No. It preserves useful metadata and a reference. Correct forwarding and return remain the wrapper's responsibility. The wrapper adds O(1) structure plus argument-collection overhead proportional to the supplied argument count, excluding the original's work.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: configure a result policy

      Add a factory layer that scales numeric results while keeping calls intact.

      The contract

      • Implement scale_result(factor): it returns a decorator, which returns a synchronous wrapped function.
      • For integer factor and integer original result, return the int product; forward args and kwargs exactly once and propagate errors.
      • Preserve metadata with wraps. Separate factories retain independent factors. No async support, retries, network or input mutation is promised.
      Transfer: configure a result policyPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. scaled result
        def f(x):
            return x + 1
        d = scale_result(3); assert callable(d); w = d(f); assert callable(w); r = w(2); assert type(r) is int and r == 9
      2. zero factor
        def f():
            return 8
        d = scale_result(0); assert callable(d); w = d(f); assert callable(w); r = w(); assert type(r) is int and r == 0
      3. negative factor
        def f(x, *, extra=0):
            return x + extra
        d = scale_result(-2); assert callable(d); w = d(f); assert callable(w); r = w(3, extra=1); assert type(r) is int and r == -8
      4. independence and metadata
        def f():
            return 2
        a = scale_result(2); b = scale_result(5); assert callable(a) and callable(b); x = a(f); y = b(f); assert callable(x) and callable(y); rx = x(); ry = y(); assert type(rx) is int and type(ry) is int and (rx, ry) == (4, 10) and x.__name__ == 'f' and x.__wrapped__ is f
      5. empty source preserved
        p = []
        def f(values):
            return sum(values)
        d = scale_result(7); assert callable(d); w = d(f); assert callable(w); r = w(p); assert type(r) is int and r == 0 and p == []
      6. deferred once and error
        calls = []
        def f(x):
            calls.append(x)
            if x < 0:
                raise ValueError('negative')
            return x + 1
        d = scale_result(2); assert callable(d); w = d(f); assert callable(w) and calls == []; r = w(3); assert type(r) is int and r == 8 and calls == [3]
        try:
            w(-1)
        except ValueError:
            assert calls == [3, -1]
        else:
            raise AssertionError('error swallowed')
        What changed from preserve_call?

        An outer closure now retains configuration, and the returned numeric value is intentionally transformed. Metadata, forwarding and exception behavior still need preservation. The added arithmetic and retained factor are constant-count operations, with integer cost depending on magnitude.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Ordering changes meaning

        Stacked decorators are applied from the bottom upward. Their wrappers then control the order of work when the resulting function is called.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Understand why validation, caching and result transformations cannot be freely reordered.

        Words you will see

        Composition
        Building one operation by applying another around it.
        Inner wrapper
        The callable installed by the decorator nearest the original definition.
        Async-aware wrapper
        A wrapper that understands coroutine execution and awaits it when that is the contract.

        Expand the composition

        The original base returns 3. @double is applied first because it is nearest def. @add_one wraps the result, so the public callable is add_one(double(base)). On invocation, double gets 3 and returns 6; add_one then returns 7.

        Swapping the two decorator lines produces double(add_one(base)), which returns 8. Both versions use the same operations, but their composition is different. Pure multiplication decorators would hide this distinction because those particular operations commute.

        Order is not only arithmetic

        Validation outside caching can run on every call, while caching outside validation may bypass later validation work. A wrapper that catches all exceptions can also hide failures from wrappers outside it. Choose and test the policy order.

        These examples are synchronous only. An async function returns a coroutine object before its body completes; a synchronous arithmetic wrapper cannot multiply or inspect the final result correctly without an async-aware await. Do not advertise this code as an async decorator.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. @double

          First wrap the original base with doubling.

        2. @add_one

          Then wrap that doubled callable with addition.

        3. return function() + 1

          The outer wrapper adds one after the inner returns six.

        Stacked decorators apply from the bottom upward. Caching before versus after validation can change what work is skipped. An async function requires an async-aware wrapper that awaits the result; a synchronous wrapper is not automatically a correct async decorator.

        Predict before you run

        What prints with the original stack?

        Noncommuting decorator orderPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Swap the stack.

        Try: Put @double above @add_one.

        The result becomes 8 because the addition is now inside the doubling.

        Change the base boundary.

        Try: Change return 3 to return 0.

        The original stack returns 1, not 0, because the outer addition still runs.

        Before you move on

        If the original returns 0, what do add_one(double(base)) and double(add_one(base)) return?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        They return 1 and 2 respectively. The different answers expose that order is part of the contract.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Observe without distorting

        An observing decorator should report what happened without changing results, suppressing exceptions or retaining arguments unnecessarily.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Count calls locally while preserving failure signals. This is not a production metrics, timing or retry system.

        Words you will see

        Observation
        Recording an event without redefining the operation's promised outcome.
        Propagation
        Letting an exception continue to the caller.
        Idempotency
        Repeating an operation has the same intended external effect as doing it once; retries must consider this.

        Record the event, not the inputs

        The wrapper increments counts['calls'] before forwarding. divide(8, 2) returns 4.0. divide(1, 0) increments the count and raises ZeroDivisionError, which the demonstration caller catches. The final count is 2 because attempts, not successes, are counted.

        The counter stores no arguments or exception objects. This avoids an ever-growing history and does not expose inputs in a log. The caller's except block explains the demonstration failure; the decorator itself does not replace it with a fake success.

        Do not confuse demonstration with instrumentation

        A real timing wrapper adds overhead and needs an appropriate monotonic clock. A retry wrapper needs bounded attempts, selected exceptions and an idempotency policy. This counter does neither and reports no timing claim.

        A plain dictionary update is not a cross-thread or cross-process synchronization design. The browser example is one local synchronous execution. Memory retained by this fixed counter is bounded, unlike an unbounded cache keyed by every observed argument.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. counts['calls'] += 1

          Record each attempted call before executing the original.

        2. return function(*args, **kwargs)

          Return a successful result or let its exception propagate.

        3. except ZeroDivisionError:

          The outer demonstration caller, not the decorator, handles the expected failure.

        4. print(counts['calls'])

          Two attempts were observed, including the failed one.

        A timing decorator adds overhead and needs a monotonic clock. A retry decorator needs limits, exception classification and idempotency awareness. Do not let a generic wrapper swallow errors or retain sensitive arguments in an unbounded cache.

        Predict before you run

        Why is the count 2?

        Count attempts without swallowing errorsPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Count only successful completions.

        Try: Store result = function(*args, **kwargs), increment afterwards, then return result.

        The final count becomes 1 because the failed call never reaches the increment.

        Confirm error propagation.

        Try: Remove the outer try/except and call divide(1, 0) directly.

        A real ZeroDivisionError stops execution; the wrapper does not fabricate a fallback.

        Before you move on

        If counting moved after function returns, would the failed division be counted?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. The exception skips the later increment. Decide whether the metric means attempts or successful completions and test that distinction.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.