ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
from contextlib import contextmanager
@contextmanager
def cm():
    print("setup")
    yield 1
    print("teardown")
with cm() as v:
    print("body", v)
  1. A. setup body 1 teardown
  2. B. setup teardown body 1
  3. C. body 1 setup teardown
  4. D. setup body 1

Correct answer: A. setup body 1 teardown

@contextmanager splits the generator at yield: code before yield runs as __enter__ (printing 'setup' and giving v=1), the with-body runs next ('body 1'), and code after yield runs as __exit__ ('teardown').

More Python Programming questions

Exams that ask this topic