In this Python article we want to learn about Python Function Decorators, function decorators are powerful tool for modifying and enhancing the behavior of functions. with decorators you can add functionality to a function without changing its source code. Decorators can be used for different purposes, from logging to memorization to performance profiling. you can create decorators in different ways.
One way of creating decorators is to use randomization. for example you want to create a decorator that randomly modifies the output of a function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import random def random_decorator(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) if random.randint(0, 1) == 0: return result.upper() else: return result.lower() return wrapper @random_decorator def greet(name): return f"Hello {name}" print(greet("GeeksCoders")) print(greet("John")) |
In this example random_decorator randomly converts the output of the greet function to uppercase or lowercase.
This will be the result
Another way for creating Python decorators is to use external APIs or services. for example, you want to create a decorator that adds random image or quote to the output of functions by calling an external API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import requests def random_image_decorator(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) response = requests.get("https://api.unsplash.com/photos/random", params={"orientation": "landscape", "client_id": "<UNSPLASH_CLIENT_ID>"}) if response.ok: image_url = response.json()["urls"]["regular"] return f"{result}\n{image_url}" else: return result return wrapper @random_image_decorator def greet(name): return f"Hello {name}" print(greet("GeeksCoders")) print(greet("John")) |
In this example random_image_decorator calls Unsplash API to retrieve random landscape image and adds it to the output of the greet function.