Why won't this decorator work?

MRAB python at mrabarnett.plus.com
Sat Jul 2 19:33:33 CEST 2011


On 02/07/2011 17:56, John Salerno wrote:
> I thought I had finally grasped decorators, but the error I'm getting
> ('str' type is not callable) is confusing me. Here is my code. Also,
> the commented sentence is from the Python docs, which says it doesn't
> even need to be callable, if that matters. I also commented out a few
> things in the move method. They were just to see if it would work, but
> those lines raised even more errors!
>
> import random
>
> #space = 0
>
> def move(roll):
> #    global space
> #   space += roll
>      return 'You moved to space {0}.'.format(roll)
>
> @move
> def roll_die():
>      return random.randint(1, 6)
>
> # The return value of the decorator need not be callable
> # roll_die = move(roll_die)
>
>
>
> I tried running the command "roll_die()" and I get the error message.
>
> Thanks.

A decorator should return a callable.

This:

     @move
     def roll_die():
         return random.randint(1, 6)

is equivalent to this:

     def roll_die():
         return random.randint(1, 6)

     roll_die = move(roll_die)

You should be defining a function (a callable) and then passing it to a
decorator which returns a callable.

As it is, you're defining a function and then passing it to a decorator
which is returning a string. Strings aren't callable.



More information about the Python-list mailing list