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

book
Python 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:

python
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.

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

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 5. Capitolo 2

Chieda ad AI

expand
ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt