Search code examples
pythondecoratorpython-decorators

Can variables be decorated?


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.


Solution

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