Python / Core Python Fundamentals Interview Questions
What is a context manager in Python and how do you implement one?
A context manager controls setup and teardown around a block of code via the with statement. The canonical example is file handling, but context managers are used for database transactions, locking, temporary directory creation, patching in tests, and any resource that needs guaranteed cleanup.
Python calls __enter__ when entering the with block and __exit__ when leaving it — even if an exception is raised. The value returned by __enter__ is bound to the as variable.
class Timer:
import time
def __enter__(self):
self._start = self.time.perf_counter()
return self # bound to 'as t'
def __exit__(self, exc_type, exc_val, exc_tb):
self.elapsed = self.time.perf_counter() - self._start
print(f'Elapsed: {self.elapsed:.4f}s')
return False # False = do not suppress exceptions
with Timer() as t:
result = sum(range(1_000_000))
print(t.elapsed)The simpler way for most cases is contextlib.contextmanager, which turns a generator function into a context manager — everything before yield is setup, everything after is teardown:
from contextlib import contextmanager
@contextmanager
def managed_connection(dsn):
conn = connect(dsn)
try:
yield conn # the value of 'conn' in 'with ... as conn'
finally:
conn.close() # runs even if an exception occurred
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
