[Tutor] Why use decorators ?

Lie Ryan lie.1296 at gmail.com
Sat May 2 17:39:34 CEST 2009


sudhanshu gautam wrote:
> 1.import pyglet
> window=pyglet.window.Window()
> 
> lable=pyglet.text.Lable('Hello, world',
>  font_name='Times New Roman',
>  font_size=36,
>  x=window.width//2, y=window.height//2,
>  anchor_x='center', anchor_y='center')
> *@window.event  *
> def on_draw():
>     window.clear()
>     label.draw()
> pyglet.app.run()
> 
> okay I just drop second example just tell me why we are using that all 
> the code that is showed in RED color .

I never used pyglet, but by reading the documentation it seems that the 
decorator is used to register the on_draw() function to the event loop. 
As you know, decorator is merely a syntax sugar for calling a function 
like this:

def on_draw():
     ...
on_draw = window.event(on_draw)

I guess the function window.event is the function to register the 
on_draw() function as the event handler of the window event. In this 
specific case, the window.event() internally will call the 
window.set_handler() with the appropriate arguments.

My guess is the window.event() function contains something similar to this:

def event(self, f):
     window.add_handler(f.__name__, f)
     return f

(of course with a bit more elaborations since it seems it also accept 
string argument to replace the f.__name__)



More information about the Tutor mailing list