Course Content
Intermediate Python Techniques
Intermediate Python Techniques
Syntax
Decorator works by taking a function as an argument and then executing it within a wrapper function.
To apply a decorator, one can use the @ symbol followed by the decorator function's name, placed right above the function that needs to be modified. Here's an example:
In this example, both methods achieve the same outcome. The first method, using the @
symbol, is a more readable and concise way to apply decorators
, often referred to as "syntactic sugar".
It's typical to use a nested function named wrapper
within decorators.
Flexible Decorators: Accommodating Diverse Function Arguments
Functions often require a varying number of arguments.
To develop a decorator capable of being applied to functions with differing argument counts, it's effective to utilize *args
and **kwargs
in the wrapper()
function.
def indicate(func): def wrapper(*args, **kwargs): print("=" * 15) print("Taken arguments:", *args, kwargs) result = func(*args, **kwargs) print("=" * 15) return result return wrapper @indicate def avg_two(a, b): '''Calculate the average of two numbers''' return round((a + b) / 2, 1) @indicate def avg_three(a, b, c): '''Calculate the average of three numbers''' return round((a + b + c) / 3, 1) @indicate def avg_many_kwargs(**kwargs): '''Calculate the average of multiple numbers in a dictionary''' keys = 0 total = 0 for value in kwargs.values(): keys += 1 total += value return round(total / keys, 1) print("Returned:", avg_two(14, 21), "\n") print("Returned:", avg_three(225, 12, 11), "\n") print("Returned:", avg_many_kwargs(first=51, second=11, third=47, fourth=93))
Thanks for your feedback!