Python
Context Manager
Custom context managers.
By EZ4Code Team
contextwith
Code
from contextlib import contextmanager
@contextmanager
def timer(name):
import time
start = time.time()
try:
yield
finally:
print(f"{name}: {time.time() - start:.2f}s")
with timer("operation"):
sum(range(1000000))
# Class-based implementation
class FileManager:
def __init__(self, path, mode):
self.path = path
self.mode = mode
def __enter__(self):
self.f = open(self.path, self.mode)
return self.f
def __exit__(self, *exc):
self.f.close()Explanation
Context managers ensure resources are properly released; contextmanager simplifies implementation.
More Python Snippets
Sort Dictionary by Value
Sort a Python dictionary by its values in descending order.
List Comprehension
Quickly generate lists using list comprehensions.
Dictionary Merging
Multiple ways to merge dictionaries.
File Read/Write
Various ways to read and write files.
CSV Processing
Read and write CSV files using the csv module.
JSON Processing
JSON serialization and deserialization.