Why won't this decorator work?

Ben Finney ben+python at benfinney.id.au
Sat Jul 2 18:36:47 EDT 2011


John Salerno <johnjsal at gmail.com> writes:

> Basically what I want to do is this: I first to need to roll a die to
> get a random number, then pass that number to the move method of a
> Player class. Can this be done with a decorator, or is it better just
> to do it like move(roll_die()) and be done with it?

If what you want can be expressed with ‘player.move(roll_die())’, I'm
confused as to why you think decorators would help.


A decorator is syntactic sugar for something quite different::

    @foo(spam, eggs)
    @bar
    def baz(beans):
        """ … """

is equivalent to::

    def baz(beans):
        """ … """

    baz = foo(spam, eggs)(bar(baz))

except in the first instance, the function defined never gets bound to
the name ‘baz’ even temporarily.

* The function ‘baz’ is defined, resulting in a function object. (In the
  first example, it is never bound to the name ‘baz’.)

* The expression ‘bar’ is evaluated, and the result (probably a function
  named ‘bar’) is called with the function object defined as ‘baz’; the
  return value should be a new function.

* The expression ‘foo(spam, eggs)’ is evaluated, and the result (the
  return value from that function call) is itself called, passing the
  return value from the call to ‘bar’.

* Finally, the return value from all of that is bound to the name ‘baz’.

Note that, in both ways of writing that, ‘baz’ is never called, but
instead the function object ‘baz’ is used as a parameter. Also, the
original function defined as ‘baz’ is no longer accessible.


That seems quite unrelated to your stated requirements. If you're not
accustomed to passing function objects around as data, that can be
difficult to wrap your head around; if you didn't know you needed it,
you probably don't in this case.

-- 
 \     “Jealousy: The theory that some other fellow has just as little |
  `\                                         taste.” —Henry L. Mencken |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list