Decorating function or method in python is wonderful.
@dec2
@dec1
def func(arg1, arg2, ...):
pass
#This is equivalent to:
def func(arg1, arg2, ...):
pass
func = dec2(dec1(func))
I was wondering if decorating variable in python is possible.
@capitalize
@strip
foo = ' foo '
print foo # 'FOO'
#This is equivalent to:
foo = foo.strip().upper()
I couldn't find anything on the subject via searching.
Decorators are also a powerful tool in Python which are implemented using closures and allow the programmers to modify the behavior of a function without permanently modifying it.
By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.
Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated. Using decorators in Python also ensures that your code is DRY(Don't Repeat Yourself).
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of a function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.
No, decorator syntax is only valid on functions and classes.
Just pass the value to the function:
foo = capitalize(strip(' foo '))
or replace the variable by the result:
foo = ' foo '
foo = capitalize(strip(foo))
Decorators exist because you can't just wrap a function or class declaration in a function call; simple variables you can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With