Quiz de 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.

Médio 10 perguntas ~6 minutos Aprovação com 80% Python 3.12

Escolha um modo

Jogando como visitante: entre para guardar seu XP e sua sequência.

Pergunta de exemplo

Pergunta 1 de 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=" ")
Mostrar a resposta

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

O que este quiz cobre

  • 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

Perguntas frequentes

Preciso de uma conta?

Não. Qualquer pessoa pode jogar. Entre para guardar seu XP, sequência, badges e histórico.

Qual versão do Python?

Python 3.12. Toda pergunta sobre a saída foi conferida rodando o código.

Posso refazer?

Pode. Sua melhor nota fica salva, e as perguntas e respostas são embaralhadas a cada vez.