Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre 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

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 2

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Suggested prompts:

Can you explain how the `temporary_setting` context manager works step by step?

What are some other use cases for the `@contextmanager` decorator?

How does this approach compare to writing a full context manager class?

Awesome!

Completion rate improved to 8.33

bookGenerator-based Context Managers with contextlib

Glissez pour afficher le 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

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 2
some-alt