19

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
taesu
  • 4,482
  • 4
  • 23
  • 41
  • 2
    [How can I decorate an instance of a callable class?](http://stackoverflow.com/q/24122444/2301450) – vaultah Sep 15 '15 at 15:08

1 Answers1

21

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343