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.

3
  • I recommend reading this decorator tutorial if you haven't read it yet.
    – flornquake
    Commented Sep 6, 2013 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
    Commented Sep 6, 2013 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.
    Commented Sep 7, 2013 at 0:21

1 Answer 1

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?

3
  • 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.
    Commented Sep 6, 2013 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.
    Commented Sep 6, 2013 at 23:12
  • Exactly, it's only syntactic sugar. Commented Sep 6, 2013 at 23:14

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.