Decorators

advanced-python-patterns
Wrap a function to add behavior without changing its body.
  • Level: Intermediate
  • Estimated time: 25–40 minutes
  • You will learn: Wrap a function to add behavior without changing its body.
  • Practice in: VS Code, Jupyter, or Colab

Questions

  • What problem does Decorators help us solve in a small Python program?
  • What should we predict before running the example?
  • What value, output, or error should we inspect after changing one line?

Objectives

  • Run a complete example for decorators in Colab.
  • Explain the example line by line using plain language.
  • Change one part of the code and predict the result before running it.
  • Recognize one common mistake and use the error message as evidence.

Hands-on episode: Decorators

A decorator is a function that takes a function and returns a new function, often a wrapper that runs code before or after the original function.

We will learn this by running code, not by memorizing a definition first. Open the Colab notebook from the button above, find this section, and run each cell in order. Keep a small note beside the notebook with three columns: prediction, actual result, and what changed.

Example 1.1

Read the manual wrapper idea before focusing on the @ syntax.

def announce(func):
def wrapper():
print("Starting")
func()
print("Done")
return wrapper

@announce
def greet():
print("Hello")

greet()

Run the cell once without editing it. If the result is different from your prediction, leave the prediction visible and write one sentence about the difference. That sentence is more useful than a perfect first guess.

Explain Example 1.1

  • announce receives another function as its input.
  • wrapper describes the extra behavior around the original function call.
  • return wrapper gives back the replacement function.
  • @announce applies that replacement to greet before you call it.

Now explain the example out loud or in a Markdown cell. Use short sentences: “this line creates…”, “this name stores…”, “this output appears because…”. If you cannot explain a line yet, run only the lines above it and inspect the values that exist at that moment.

Challenge 1.1

NoteChallenge

Remove @announce and call greet() again. The core function still works, but the starting and done messages disappear because the wrapper is no longer applied.

Show a safe way to approach the challenge
  1. Copy Example 1.1 into a new Colab cell.
  2. Change exactly one value, name, condition, or line.
  3. Write the expected output before running the cell.
  4. Run the cell and compare the actual result with your prediction.
  5. If the result surprises you, undo the change and try a smaller one.

Suggested first move: Remove @announce and call greet() again.

Debugging checkpoint 1.1

WarningDebugging checkpoint

A common decorator bug is calling the function too early: write func, not func(), when you mean to pass the function itself. Also remember to return the wrapper. In real code, use functools.wraps to preserve the original function’s name and documentation.

Do not debug by rewriting the whole example. Read the error type or surprising output, inspect the closest value with print(...) or type(...), then change one thing. This is the same routine you will use in larger projects.

Apply it

Write a decorator that prints a message before a no-argument function runs. Then add functools.wraps and inspect the function name before and after.

Finish by adding a Markdown cell that answers: What did this example teach me that I can reuse in a project?

Key points

  • Learn the concept by running a complete, small example first.
  • Predict before execution so your thinking becomes visible.
  • Change one thing at a time so cause and effect stay clear.
  • Treat errors as clues about the exact line or value Python could not handle.

Why this matters

Wrap a function to add behavior without changing its body.

Beginners often try to learn Python as a list of commands. This lesson teaches one idea at a time: what problem it solves, how to recognize it in code, how to practice it, and how to debug a common mistake. Treat the code examples as small experiments, not as text to memorize.

NoteGuiding questions

By the end of this lesson, you should be able to answer:

  • What problem does Decorators help me solve?
  • What words or symbols should I recognize in a small example?
  • What should I check first when the example does not behave as expected?
NoteLearning objectives

You will practice how to:

  • explain the main idea in everyday language;
  • read a short example line by line;
  • predict the result before running the code;
  • make one safe variation of the example;
  • debug one common beginner mistake.
TipAnalogy

A decorator is like putting a protective cover on a book: the story remains, but the outside behavior changes.

How a decorator wraps a function

A decorator receives a function, builds a wrapper around it, and gives the wrapped function back under the original name.

flowchart LR
  original["original function<br/>greet"] --> decorator["decorator<br/>@announce"]
  decorator --> wrapper["wrapper function<br/>adds behavior"]
  wrapper --> name["name greet<br/>now points to wrapper"]
  name --> call["greet() runs wrapper<br/>then original function"]

This is why decorators are powerful: they change how a function is called without rewriting the function body.

Vocabulary

  • decorator — a key term for this lesson; after the example, write a one-sentence definition in your own words.
  • wrapper — a key term for this lesson; after the example, write a one-sentence definition in your own words.
  • function object — a key term for this lesson; after the example, write a one-sentence definition in your own words.
  • @ syntax — a key term for this lesson; after the example, write a one-sentence definition in your own words.
  • higher-order function — a key term for this lesson; after the example, write a one-sentence definition in your own words.

What this means

A decorator is a function that takes a function and returns a modified function.

A useful explanation has three parts:

  1. Name the thing. Say what concept you are using.
  2. Name the input. Identify the values, files, objects, or settings involved.
  3. Name the result. Explain what changes, what is returned, or what is printed.

Example 1

Predict what will happen before you run the code.

def announce(function):
    def wrapper():
        print("starting")
        function()
        print("done")
    return wrapper

@announce
def greet():
    print("hello")

greet()

Step-by-step explanation

  1. def announce(function): — pause here and say what this line reads, creates, changes, or displays.
  2. def wrapper(): — pause here and say what this line reads, creates, changes, or displays.
  3. print("starting") — pause here and say what this line reads, creates, changes, or displays.
  4. function() — pause here and say what this line reads, creates, changes, or displays.
  5. print("done") — pause here and say what this line reads, creates, changes, or displays.
  6. Continue the same process for the remaining lines, one line at a time.

After running the example, compare the actual output with your prediction. If they differ, do not erase your prediction. The difference is the part that can teach you the most.

Worked example: read, predict, modify

Use this routine with every example in the course:

Step What to do Why it helps
Read Point to each name, value, and operator. Slows the code down enough to understand it.
Predict Write what you think will happen. Creates a testable prediction.
Run Execute the smallest complete example. Lets Python give evidence.
Explain Say what happened in plain language. Converts recognition into understanding.
Modify Change one small thing and run again. Shows which part caused which result.

Challenge

NotePractice

Change one input value, predict the new output, run the code, and explain the difference in one sentence.

Show one possible solution path
  1. Copy Example 1 into Colab, Jupyter, or a .py file.
  2. Mark the line you plan to change.
  3. Write a one-sentence prediction.
  4. Run the changed code.
  5. If the result surprises you, restore the original and change a smaller part.

The goal is not to find the only correct answer. The goal is to create a small experiment where you can explain cause and effect.

Common mistakes

WarningCommon mistake

A decorator replaces the original name with the returned wrapper. Preserve arguments and metadata when writing real decorators.

When you get stuck, use this debugging routine:

  1. Read the last line of the error message or inspect the unexpected output.
  2. Find the smallest line of code that could be responsible.
  3. Print or inspect the value and type at that point.
  4. Change one thing.
  5. Run again and record what changed.

Checkpoint quiz

Answer these questions before moving on. The quiz runs with Quarto OJS in the browser, so it does not need a Python kernel during website rendering.

Notebook and Colab practice

Open a blank notebook at https://colab.new, copy Example 1, and run three small variations. You can also use a local Jupyter notebook or VS Code. Keep one cell for the original example, one cell for your prediction, and one cell for your modified version.

Instructor note

Teaching notes
  • Ask learners to predict before execution; do not skip this step.
  • Invite one learner to explain the analogy and another to explain the code.
  • When an error appears, model calm traceback reading instead of immediately fixing it.
  • If time is short, keep Example 1 and quiz; move the challenge to homework.

Key points

TipKey points
  • A decorator is a function that takes a function and returns a modified function.
  • Small examples are more useful than large copied programs when a concept is new.
  • Prediction, execution, explanation, and one small modification form the core practice loop.
  • Debugging starts by reading clues and changing one thing at a time.

References

  • Python functional tools: https://docs.python.org/3/howto/functional.html
  • contextlib documentation: https://docs.python.org/3/library/contextlib.html
  • logging documentation: https://docs.python.org/3/library/logging.html
  • Python Tutorial: https://docs.python.org/3/tutorial/
  • Quarto OJS documentation: https://quarto.org/docs/interactive/ojs/
  • ipywidgets documentation: https://ipywidgets.readthedocs.io/en/stable/
Back to top