Content · Programming · Python

Python contextlib.contextmanager() Decorator: Usage and Examples

@contextmanager converts a generator with exactly one yield into a context manager.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

@contextmanager converts a generator with exactly one yield into a context manager.

What It Does and Why It Matters


@contextmanager converts a generator with exactly one yield into a context manager. Code before yield acquires the resource and a finally block performs cleanup.

Correct cleanup means resources are released when exceptions occur, not only on the success path.

Step-by-Step Example


Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.

from contextlib import contextmanager
@contextmanager
def track_operation(operation_name: str):
    print(f'Start {operation_name}')
    try:
        yield operation_name
    finally:
        print(f'End {operation_name}')
with track_operation('validation') as selected_operation:
    print(selected_operation)

How the Code Works


  • The imports make these standard-library tools available: contextlib.
  • The definition of track_operation creates reusable behavior; its body runs only when called or instantiated as appropriate.
  • The structured block controls error handling or resource lifetime, including what happens when an operation fails.
  • The print calls display the results. Compare these results with the method’s documented return type and the input used.
  • The manager establishes a boundary for acquiring and releasing the resource; observe the order of setup, body execution and cleanup.

Expected output:

Start validation
validation
End validation

Each displayed line comes from the corresponding calculation or check. The output helps verify the return values before you adapt the example to your own input.

Second Example: Compare Two Cases


Use a different input or a related operation to observe an important difference. The two examples help separate the general rule from one particular result.

from contextlib import contextmanager
@contextmanager
def demo():
    print("open")
    try: yield
    finally: print("close")
with demo(): print("work")

Expected output:

open
work
close

Where You Would Use This


This matters when working with files, locks, sockets and connections whose lifetime must be controlled. A reliable implementation defines ownership and releases resources on both successful and exceptional paths. Use a small with block before building a more complex manager.

Practice Exercise


Create a context manager that prints when a temporary operation starts and finishes.

Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.

Reference: official Python documentation for the complete API contract and version notes.

Common Beginner Mistakes


  • Yielding several times or placing cleanup only after yield without a finally clause.
  • Releasing the resource only on the successful path rather than when an exception interrupts the block.

Key Takeaways


  • @contextmanager converts a generator with exactly one yield into a context manager.
  • Create a context manager that prints when a temporary operation starts and finishes.
  • Correct cleanup means resources are released when exceptions occur, not only on the success path.
Share this resourceSend this page to someone who may find it useful.