Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can variables be decorated? [closed]

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.

like image 211
taesu Avatar asked Sep 15 '15 15:09

taesu


People also ask

Are decorators closures?

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.

What is a decorated function?

By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.

How do decorators work in Python?

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

What is the biggest advantage of the decorator in Python?

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.


1 Answers

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.

like image 56
Martijn Pieters Avatar answered Sep 28 '22 10:09

Martijn Pieters