Saturday 13 July 2024

5 Practical Examples to Master Python Decorators

 

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

Popular Posts

Categories

AI (31) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (146) C (77) C# (12) C++ (82) Course (67) Coursera (198) Cybersecurity (24) data management (11) Data Science (106) Data Strucures (8) Deep Learning (13) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (20) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (882) Python Coding Challenge (281) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses