Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Python Decorator Syntax: Writing and Applying Decorators | Mastering Python Decorators
Intermediate Python Techniques

bookPython Decorator Syntax: Writing and Applying Decorators

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:

def decorator(func):
    ...

# First method
@decorator
add(a,b):
    print(f"Function add: {a} + {b}")

add(2, 3)

# Second method
add(a,b):
    print(f"Function add: {a} + {b}")

inner = decorator(add)

inner(2, 3)

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.

1234567891011121314151617181920212223242526272829303132333435
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))
copy

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 5. ChapterΒ 2

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

bookPython Decorator Syntax: Writing and Applying Decorators

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:

def decorator(func):
    ...

# First method
@decorator
add(a,b):
    print(f"Function add: {a} + {b}")

add(2, 3)

# Second method
add(a,b):
    print(f"Function add: {a} + {b}")

inner = decorator(add)

inner(2, 3)

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.

1234567891011121314151617181920212223242526272829303132333435
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))
copy

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 5. ChapterΒ 2
some-alt