Quick Tip
Python context managers:
# Built-in context managers
with open('file.txt', 'r') as f:
content = f.read()
# Custom context manager
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
with FileManager('file.txt', 'w') as f:
f.write("Hello, World!")
# Using contextlib
from contextlib import contextmanager
@contextmanager
def timer():
start = time.time()
yield
end = time.time()
print(f"Elapsed: {end - start} seconds")
Powered by MonkeyCode: https://monkeycode-ai.net/
Top comments (0)