Why won't this decorator work?

John Salerno johnjsal at gmail.com
Sat Jul 2 20:08:38 CEST 2011


On Jul 2, 12:33 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:
> 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.

But why does the documentation say "The return value of the decorator
need not be callable"? 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?



More information about the Python-list mailing list