Python
Decorators
Define and use decorators.
By EZ4Code Team
decoratordecorator
Code
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} elapsed {time.perf_counter() - start:.4f}s")
return result
return wrapper
@timer
def slow_func():
time.sleep(1)
return "done"
# Decorator with arguments
def repeat(n):
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return decoExplanation
Decorators extend functionality without modifying the original function; functools.wraps preserves metadata.
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.