0

In Python, is there a way to assign different decorators to functions as variables?

For example (the following code doesn't execute, obviously):

def status_display(function):
    def body():
        print("Entering", function.__name__)
        function()
        print("Exited", function.__name__)
    return body

def call_counter(function):
    counter = 0
    def body():
        function()
        nonlocal counter
        counter += 1
        print(function.__name__, 'had been executed', counter, 'times')
    return body

def a_function():
    print('a_function executes')

# problems start here
# is there a working alternative to this false syntax?
@status_display
a_function_with_status_display = a_function()
@call_counter
a_function_with_call_counter = a_function()

# for an even crazier feat
# I knew this wouldn't work even before executing it
a_function_with_status_display = @status_display a_function()
a_function_with_call_counter = @call_counter a_function()

Thanks in advance.

Alex D.
  • 427
  • 1
  • 5
  • 14
  • I recommend reading this [decorator tutorial](http://stackoverflow.com/a/1594484) if you haven't read it yet. – flornquake Sep 06 '13 at 23:09
  • `a_function()` *with the parentheses* implies you're actually *calling* the function right there, which is probably not what you intend. (Unless `a_function` *creates* functions when it is called...) – ely Sep 06 '13 at 23:12
  • @flornquake I will. I have to learn to first think then tinker, since with me it's the other way around usually. Then again, if you think too much and don't tinker you don't learn at all. I guess it's all about balance, but if you think about it that way - the order really doesn't matter. – Alex D. Sep 07 '13 at 00:21

1 Answers1

5
a_function_with_status_display = status_display(a_function)
a_function_with_call_counter = call_counter(a_function)

You seem to be able to write decorators, but you don't know what they do?

Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
  • That was fast :) Why didn't I think of that? I'll try it out now. Gotta see if it'll work for a decorator with a non-empty argument list as well, but then again, why wouldn't it? Thanks! – Alex D. Sep 06 '13 at 23:05
  • Well I just started learning Python since Wednesday. I just realized that @thing is just a syntactic sugar for a function wrapper and not much else. – Alex D. Sep 06 '13 at 23:12
  • Exactly, it's only syntactic sugar. – Pavel Anossov Sep 06 '13 at 23:14