Why won't this decorator work?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jul 2 22:11:43 EDT 2011


John Salerno wrote:

> But why does the documentation say "The return value of the decorator
> need not be callable"? 

The thing returned by a decorator does not need to be callable, but if you
want to call it, then it better be!

This is no different from this:

my_func = "hello world"
my_func()  # fails because strings aren't callable

So if I do this:

def decorator(func):
    # ignores the function and returns a string
    return "hello world"

@decorator
def my_func():
    x = 1
    y = 2
    return x+y

print(my_func)  # prints "hello world"
my_func()  # fails because strings aren't callable


If that's useful to you, decorator syntax allows it. That is all the
documentation means.



> And why, if I remove the decorator and just 
> leave the two functions as if, does the call to move(roll_die()) work?
> Isn't that what the decorator syntax is essentially doing?

The call move(roll_die()) is similar to this:

temp = roll_die()
my_string = move(temp)

which is perfectly fine, because you never call my_string. If you did, you'd
get the same error, because strings aren't callable.

The decorator syntax is completely different. It is doing this:

# replace the function roll_die with the output of move, which is a string
roll_die = move(roll_die)  
# now try to call "roll_die", actually a string
roll_die()

which is more like:

move(roll_die)()

See the difference?



-- 
Steven




More information about the Python-list mailing list