Python-Quiz: 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.

Mittel 10 Fragen ~6 Minuten Bestanden ab 80% Python 3.12

Modus wählen

Du spielst als Gast: Melde dich an, damit XP und Serie gespeichert werden.

Beispielfrage

Frage 1 von 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=" ")
Lösung zeigen

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

Darum geht es in diesem 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

Häufige Fragen

Brauche ich ein Konto?

Nein. Jeder kann spielen. Mit Anmeldung werden XP, Serie, Abzeichen und Verlauf gespeichert.

Welche Python-Version?

Python 3.12. Jede Frage zur Ausgabe wurde geprüft, indem der Code ausgeführt wurde.

Kann ich es wiederholen?

Ja. Dein Bestwert bleibt erhalten, und Fragen und Antworten werden jedes Mal neu gemischt.