Loading

Quipoin Menu

Learn • Practice • Grow

python / Context Managers
mcq
Direction: Choose the correct option

Q1.

What is a context manager in Python?
A. A module
B. An object that defines __enter__ and __exit__
C. A decorator
D. A function with `yield`
Direction: Choose the correct option

Q2.

Which statement is used to invoke a context manager?
A. try
B. using
C. with
D. as
Direction: Choose the correct option

Q3.

What does the `__enter__` method do?
A. Returns context
B. Sets up the resource, returns the object to assign
C. Cleans up
D. Raises an error
Direction: Choose the correct option

Q4.

What does the `__exit__` method do?
A. Handles cleanup, receives exception info
B. Exits the program
D. Returns the context
Direction: Choose the correct option

Q5.

How can you create a context manager using a generator?
A. Using `yield`
B. Using `@contextmanager` decorator from `contextlib`
C. Both A and B
D. Using `__enter__` and `__exit__`
Direction: Choose the correct option

Q6.

What is the purpose of `with open('file.txt') as f:`?
A. Writes to the file
B. Opens the file
C. Reads the file
D. Ensures the file is closed after block
Direction: Choose the correct option

Q7.

What happens if an exception occurs inside the `with` block?
A. The context manager fails
B. `__exit__` is called with exception details
C. The program crashes
D. The exception is ignored
Direction: Choose the correct option

Q8.

What does the `as` clause in `with ... as` do?
A. Assigns the result of `__enter__` to a variable
B. Imports a module
C. Defines an alias
Direction: Choose the correct option

Q9.

Which library provides the `contextmanager` decorator?
A. abc
B. functools
C. contextlib
D. itertools
Direction: Choose the correct option

Q10.

What is the purpose of `contextlib.closing`?
B. Closes the context
C. Calls `close()` on the object when the block exits
D. Closes the file