Quiz Python: Context Managers & with

This Python quiz explains the with statement from the inside. You will trace __enter__ and __exit__, see how exceptions are passed to __exit__ and when they are swallowed, and build context managers with contextlib.

Medio 10 domande ~6 minuti Superato con il 80% Python 3.12

Scegli una modalità

Stai giocando come ospite: accedi per salvare XP e serie.

Domanda di esempio

Domanda 1 di 10

What does this print?

class Tag:
    def __enter__(self):
        print("enter", end=" ")
        return "body"

    def __exit__(self, *exc):
        print("exit", end="")

with Tag() as t:
    print(t, end=" ")
Mostra la risposta

B. enter body exit with calls __enter__ first and binds its return value, "body", to t. Then the block runs, and __exit__ runs last.

Cosa copre questo quiz

  • What with calls and what as receives
  • __exit__ and exceptions, including suppressing them
  • @contextmanager with yield and try/finally
  • Several managers in one with and their exit order
  • contextlib.suppress

Domande frequenti

Serve un account?

No. Chiunque può giocare. Accedi per salvare XP, serie, badge e cronologia.

Quale versione di Python?

Python 3.12. Ogni domanda sull'output è stata verificata eseguendo il codice.

Posso rifarlo?

Sì. Il tuo miglior punteggio resta salvato, e domande e risposte vengono mescolate ogni volta.