Technology Decorators and Context Managers | Python Tutorial

Learn with diagrams, code, systems and practical examples.

</>
TutorialsPythonDecorators and Context Managers
Advanced Python · Chapter 23

Decorators and Context Managers

Wrap behavior and manage resource lifecycles with common Python patterns.

Why this matters

Decorators and context managers appear throughout web frameworks, testing tools, logging, files, locks, and transactions.

Start with the idea

A decorator receives a function and returns a wrapped function. A context manager defines setup and cleanup around a block used with the with statement.

IdeaUnderstand the purpose
CodeRun the smallest example
PracticeChange it yourself
SubjectVision learning pattern: understand the idea before memorizing syntax.

Small working example

Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.

Python
from contextlib import contextmanager

@contextmanager
def section(name):
    print("start", name)
    yield
    print("end", name)

with section("demo"):
    print("work")
Expected output
start demo
work
end demo
What to notice

The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.

Common beginner mistake

Mistake

Using decorators for hidden side effects that make normal function behavior surprising.

Better approach

Use wrappers when cross-cutting behavior is clear, documented, and easier than repeating it everywhere.

Quick recap

  • Decorators wrap callable behavior.
  • Context managers manage setup and cleanup.
  • Both should make lifecycle or cross-cutting behavior clearer.

Try it yourself

These are deliberately small. If you can complete them without copying the example, you are ready to continue.

  1. Write a simple timing decorator.
  2. Create a context manager that prints before and after a block.