Why won't this decorator work?

John Salerno johnjsal at gmail.com
Sun Jul 3 04:14:59 CEST 2011


On Jul 2, 9:11 pm, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> 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

Eesh, ok, I think I *still* don't quite get decorators, but I get it a
little more now. Definitely not what I needed to do here. :)



More information about the Python-list mailing list