Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Generator-based Context Managers with contextlib | Custom Context Managers
Python Context Managers

bookGenerator-based Context Managers with contextlib

12345678910111213141516171819202122
from contextlib import contextmanager @contextmanager def temporary_setting(settings_dict, key, temp_value): original_value = settings_dict.get(key) settings_dict[key] = temp_value try: yield finally: if original_value is None: del settings_dict[key] else: settings_dict[key] = original_value # Usage settings = {"theme": "dark", "volume": 80} print("Before:", settings) with temporary_setting(settings, "theme", "light"): print("Inside context:", settings) print("After:", settings)
copy

The contextlib.contextmanager decorator lets you write a context manager using a generator function. This approach simplifies resource management when you only need to set up and tear down resources, without needing a full class. In the code sample above, the temporary_setting function changes a value in a dictionary for the duration of the context and then restores the original value.

When you use the @contextmanager decorator, the function you write must be a generator, meaning it must use the yield statement. Everything before yield runs when entering the context (the code inside the with block). Everything after yield runs when exiting the context, even if an exception occurs. The try...finally structure ensures that the cleanup code always runs. This pattern is ideal for temporary changesβ€”such as modifying a setting, opening a resource, or changing an environment variableβ€”and then reliably undoing those changes afterward.

question-icon

Fill in the blanks to complete a generator-based context manager that temporarily changes a value in a dictionary and restores it after the context:

from contextlib import contextmanager @contextmanager def temporary_change(d, key, value): old = d.get(key) d[key] = value try: finally: if old is None: del d[key] else: d[key] = old

Click or drag`n`drop items and fill in the blanks

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 2

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Awesome!

Completion rate improved to 8.33

bookGenerator-based Context Managers with contextlib

Swipe to show menu

12345678910111213141516171819202122
from contextlib import contextmanager @contextmanager def temporary_setting(settings_dict, key, temp_value): original_value = settings_dict.get(key) settings_dict[key] = temp_value try: yield finally: if original_value is None: del settings_dict[key] else: settings_dict[key] = original_value # Usage settings = {"theme": "dark", "volume": 80} print("Before:", settings) with temporary_setting(settings, "theme", "light"): print("Inside context:", settings) print("After:", settings)
copy

The contextlib.contextmanager decorator lets you write a context manager using a generator function. This approach simplifies resource management when you only need to set up and tear down resources, without needing a full class. In the code sample above, the temporary_setting function changes a value in a dictionary for the duration of the context and then restores the original value.

When you use the @contextmanager decorator, the function you write must be a generator, meaning it must use the yield statement. Everything before yield runs when entering the context (the code inside the with block). Everything after yield runs when exiting the context, even if an exception occurs. The try...finally structure ensures that the cleanup code always runs. This pattern is ideal for temporary changesβ€”such as modifying a setting, opening a resource, or changing an environment variableβ€”and then reliably undoing those changes afterward.

question-icon

Fill in the blanks to complete a generator-based context manager that temporarily changes a value in a dictionary and restores it after the context:

from contextlib import contextmanager @contextmanager def temporary_change(d, key, value): old = d.get(key) d[key] = value try: finally: if old is None: del d[key] else: d[key] = old

Click or drag`n`drop items and fill in the blanks

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 2
some-alt