wrtite a python with decorator example
- User
wrtite a python with decorator example
Assistant
Sure! Here's a simple Python example with a decorator:
def log_function_call(func): def wrapper(*args, **kwargs): print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}") result = func(*args, **kwargs) print(f"Function returned: {result}") return result return wrapper @log_function_call def calculate_sum(a, b): return a + b result = calculate_sum(2, 3) print(f"Result: {result}")In this example, we define a decorator
log_function_callthat takes a function as an argument. The decorator creates a new function (calledwrapper) that logs the function name, arguments, and return value. The original function (calculate_sum) is passed as an argument towrapper.We then use the
@syntax to decorate thecalculate_sumfunction withlog_function_call. This creates a new function with the namecalculate_sumand replaces the originalcalculate_sumwith it. When we callcalculate_sum, thewrapperfunction is called instead, which logs the function call and returns the result of the original function.This allows us to easily add logging functionality to any function without having to modify the original code.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.