Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Generator-based Context Manager | Custom Context Managers
Python Context Managers

bookChallenge: 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.

Oppgave

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_value to new_value before yielding.
  • The original value of some_value must be restored after the context completes, regardless of how the context is exited.

Løsning

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 4
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

close

Awesome!

Completion rate improved to 8.33

bookChallenge: Generator-based Context Manager

Sveip for å vise menyen

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.

Oppgave

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_value to new_value before yielding.
  • The original value of some_value must be restored after the context completes, regardless of how the context is exited.

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 4
single

single

some-alt