5. Decorator for Timing
A decorator to measure the execution time of a function.
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} executed in {end_time - start_time} seconds")
return result
return wrapper
@timer
def slow_function():
time.sleep(2)
return "Finished"
print(slow_function())
#clcoding.com
slow_function executed in 2.001049518585205 seconds
Finished
4. Decorator for Caching
A decorator to cache the results of expensive function calls.
def cache(func):
cached_results = {}
def wrapper(*args):
if args in cached_results:
return cached_results[args]
result = func(*args)
cached_results[args] = result
return result
return wrapper
@cache
def slow_function(x):
print(f"Computing {x}...")
return x * x
print(slow_function(4))
print(slow_function(4))
print(slow_function(5))
#clcoding.com
Computing 4...
16
16
Computing 5...
25
3. Decorator for Logging
A decorator to log function calls and their arguments.
def logger(func):
def wrapper(*args, **kwargs):
print(f"Function {func.__name__} called with args: {args} and kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} returned {result}")
return result
return wrapper
@logger
def add(a, b):
return a + b
add(3, 5)
#clcoding.com
Function add called with args: (3, 5) and kwargs: {}
Function add returned 8
8
2. Decorator with Arguments
A decorator that accepts arguments to customize its behavior.
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Clcoding")
#clcoding.com
Hello, Clcoding!
Hello, Clcoding!
Hello, Clcoding!
1. Basic Decorator
A simple example to understand the basic structure and functionality of decorators.
def simple_decorator(func):
def wrapper():
print("Before the function runs")
func()
print("After the function runs")
return wrapper
@simple_decorator
def say_hello():
print("Hello!")
say_hello()
#clcoding.com
Before the function runs
Hello!
After the function runs
0 Comments:
Post a Comment