averainy's Blog

averainy

29 May 2024

How to Use Decorators to Print Log in Python

  1. creat a decorator:
def logDecorator(func):
    def wrapper(*args, **kwargs):
        print(f"Call function {func.__name__} with args {args} and kwargs {kwargs}")
        result = func(*args, **kwargs)
        print(f"Function {func.__name__} returned {result}")
        return result
    return wrapper
  1. use this decorator
@logDecorator
def add(x, y):
    return x + y

full code:

def logDecorator(func):
    def wrapper(*args, **kwargs):
        print(f"Call function {func.__name__} with args {args} and kwargs {kwargs}")
        result = func(*args, **kwargs)
        print(f"Function {func.__name__} returned {result}")
        return result
    return wrapper
@logDecorator
def add(x, y):
    return x + y

console print log:

Call function add with args (3, 5) and kwargs {}
Function add returned 8
8