Content · Programming · Python

Python Generator-Based vs Class-Based Context Managers

Class-based context managers define __enter__ and __exit__; generator-based managers use @contextmanager and yield.

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

Class-based context managers define __enter__ and __exit__; generator-based managers use @contextmanager and yield.

What It Does and Why It Matters


Class-based context managers define __enter__ and __exit__; generator-based managers use @contextmanager and yield. Both enable deterministic cleanup, but classes suit reusable state and richer protocols.

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
class Session:
    def __enter__(self):
        return 'class session'
    def __exit__(self, exception_type, exception_value, traceback_value):
        return False
@contextmanager
def generator_session():
    yield 'generator session'
with Session() as first_session, generator_session() as second_session:
    print(first_session, second_session)

How the Code Works


  • The imports make these standard-library tools available: contextlib.
  • The definition of Session, generator_session 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.

Expected output:

class session generator session

For the demonstrated inputs, Python displays 'class session generator session'. This result follows from the operation described above; change one input at a time to understand which rule matters.

What to Notice


Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.

If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.

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


Compare a minimal class manager with an @contextmanager implementation.

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


  • Returning True from __exit__ accidentally and swallowing exceptions without intending to.
  • Releasing the resource only on the successful path rather than when an exception interrupts the block.

Key Takeaways


  • Class-based context managers define __enter__ and __exit__; generator-based managers use @contextmanager and yield.
  • Compare a minimal class manager with an @contextmanager implementation.
Share this resourceSend this page to someone who may find it useful.