Python

Context Managers

21 flashcards · answers and spaced-repetition review in the KnowCard app

A context manager class must implement which two magic methods, and when is each called?
Why prefer with open(...) as f: over f = open(...) followed by manual cleanup?
In with EXPR as name:, what gets bound to name — the object in EXPR, or something else?
If the with body raises an exception, does __exit__ still run?
What are the three arguments passed to __exit__, and what are they when no exception occurred?
Inside __exit__, what does returning True do to an exception raised in the with body?
Does returning a non-True truthy value (e.g. 1 or "ok") from __exit__ suppress the exception, like True would? Be precise.
What does this print? ``` class CM: def __enter__(self): return self def __exit__(self,*a): print("exit") with CM(): raise ValueError("boom") print("after") ```
With @contextlib.contextmanager, how does the decorated generator split into setup and teardown?
In a @contextmanager generator, why wrap the yield in try/finally instead of just putting cleanup after it?
How does with a() as x, b() as y: differ from opening a and b in two separate nested with statements?
When a contextlib.ExitStack block exits, in what order are the stacked managers' __exit__ methods called?
What does with contextlib.suppress(IndexError): do, and how is it different from an empty except?
You have an object with a .close() method but no __enter__/__exit__. How do you use it with with?
You want code to *optionally* run inside a context manager (e.g. redirect stdout only sometimes). What goes in the "do nothing" branch?
What side effect does contextlib.redirect_stdout(f) have that you must watch for?
In a class-based context manager, can the entry/work method be safely called outside a with block?
What does this print? ``` with open("f") as a, open("g") as b: pass # which closes first, a or b? ```
Two context managers on one with line make it too long. Besides a trailing backslash, what syntax lets you break it across lines, and since which Python version?
A class already frees its resource in __del__. Why is that not as reliable as freeing it in a context manager's __exit__?
contextlib.redirect_stdout(f) captures print output. You now need to capture the error stream instead — what do you use?

Start learning today

Free to start — download the app or use it in your browser.

Get it on App StoreGet it on Google Play
Context Managers (Python) · KnowCard