Challenge: Generator-based Context Manager
In this challenge, you will apply your understanding of generator-based context managers using the contextlib.contextmanager decorator. Your goal is to create a context manager that can temporarily change the value of a variable during the context and restore its original value afterward. This is a common pattern when you need to alter global or module-level state in a controlled and reversible way.
Swipe to start coding
Create a generator-based context manager using contextlib.contextmanager that temporarily sets the global variable some_value to a new value for the duration of the context. When the context exits, the original value of some_value must be restored.
- The context manager must set
some_valuetonew_valuebefore yielding. - The original value of
some_valuemust be restored after the context completes, regardless of how the context is exited.
Lösning
Tack för dina kommentarer!
single
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Can you show me an example of how to use such a context manager?
What are some common use cases for temporarily changing a variable's value?
Could you explain how the `contextlib.contextmanager` decorator works?
Awesome!
Completion rate improved to 8.33
Challenge: Generator-based Context Manager
Svep för att visa menyn
In this challenge, you will apply your understanding of generator-based context managers using the contextlib.contextmanager decorator. Your goal is to create a context manager that can temporarily change the value of a variable during the context and restore its original value afterward. This is a common pattern when you need to alter global or module-level state in a controlled and reversible way.
Swipe to start coding
Create a generator-based context manager using contextlib.contextmanager that temporarily sets the global variable some_value to a new value for the duration of the context. When the context exits, the original value of some_value must be restored.
- The context manager must set
some_valuetonew_valuebefore yielding. - The original value of
some_valuemust be restored after the context completes, regardless of how the context is exited.
Lösning
Tack för dina kommentarer!
single