Contenido del Curso
Intermediate Python: Arguments, Scopes and Decorators
Intermediate Python: Arguments, Scopes and Decorators
Practical Examples of Decorator Usage
Decorators in Python are a powerful tool for modifying the behavior of functions or methods. The most common usages are sleeping, timing validation, and logging.
1. Sleeping Decorator
This decorator will make the function wait for a specified amount of time before executing.
import time def sleep_decorator(seconds): def decorator(func): def wrapper(*args, **kwargs): print(f"Sleeping for {seconds} seconds before executing '{func.__name__}'") time.sleep(seconds) return func(*args, **kwargs) return wrapper return decorator @sleep_decorator(2) def my_function(): print("Function executed!") # Usage my_function()
2. Validation Decorator
This decorator checks if the inputs to a function meet certain criteria.
def validate_decorator(func): def wrapper(number): if not isinstance(number, int) or number < 0: raise ValueError("Input must be a non-negative integer") return func(number) return wrapper @validate_decorator def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) # Usage print(factorial(5)) # factorial(-1) # This will raise an error
3. Timing Decorator
This decorator measures the execution time of a function. We have already used it previous chapter.
import time def timing_decorator(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 @timing_decorator def some_function(): time.sleep(1) # Simulating a task print("Function completed") # Usage some_function()
The decorator for login verification uses additional libraries and is used in website development, so it is more appropriate to consider this decorator in the context of website creation.
As we said, decorators are a complex topic in Python and sometimes require more practice to fully understand this topic. You are on the right path in building a programmer's mindset.
Download notes on the course. 😉
¡Gracias por tus comentarios!