2025年1月3日金曜日

How to use "decorator" in python programming

 In Python, decorators are a powerful way to modify the behavior of functions or classes without directly changing their code.

Here's a breakdown:

1. Basic Concept:

  • A decorator is essentially a function that takes another function as an argument and returns a new function that adds some1 extra functionality to the original function.

2. Syntax:

Python
def my_decorator(func):
    def wrapper():
        # Code to be executed before the original function
        print("Something is happening before the function is called.")
        func() 
        # Code to be executed after the original function
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello() 

Explanation:

  • my_decorator is a decorator function that takes func (the function to be decorated) as an argument.
  • wrapper is a new function that:
    • Executes some code before calling func.
    • Calls the original func.
    • Executes some code after calling func.
  • @my_decorator above say_hello() is a syntactic sugar equivalent to: say_hello = my_decorator(say_hello)

3. Common Use Cases:

  • Logging: Log function calls, arguments, and return values.
  • Timing: Measure the execution time of a function.
  • Authentication: Check if a user is authenticated before allowing access to a function.
  • Caching: Cache the results of a function call to improve performance.

4. Example (Timing):

Python
import time

def timer(func):
    def wrapper():
        start_time = time.time()
        result = func()
        end_time = time.time()
        print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds to execute.")
        return result
    return wrapper

@timer
def my_slow_function():
    # Simulate a long-running task
    time.sleep(2) 
    return "Done!"

result = my_slow_function() 
print(result) 

Key Points:

  • Decorators can significantly improve the structure and maintainability of your code.
  • They provide a clean and elegant way to add extra functionality to existing functions.
  • Understanding decorators is essential for working with more advanced Python concepts.

I hope this explanation is helpful!