[Tutor] real world decorators

Patrick Sabin patrick.just4fun at gmail.com
Mon Sep 21 13:21:26 CEST 2009


John wrote:
> Hi,
> 
> I think I understand what decorators are and how they work.  Maybe it's just 
> me but I don't know where I'd use them in my real world programming.  I see 
> how they work with profile or coverage but does anyone have real world uses.  

@classmethod, @staticmethod, @property, @abstractclass, 
@abstractproperty are in my opinion the most import. Some toolkits use 
them too.

> I mostly create wxPython apps and don't see where they might apply.


The wx toolkit is designed to work with C++ and wxPython is just a 
language binding for it. As far as I know C++ doesn't support Decorators 
or something similar like it. So there won't be many uses for decorators 
in wx apps.

> I know the tutors will enlighten me!

Some ideas for decorators, if you want to play around with them:

@fireandforget
	Make a function call in another thread, so you can return
	immediately - without returning result. This could be for
	example useful to send an email without needing to wait, until
	it is sent.
@cache
	Cache the results of a function in a dictionary. If the function
	is called look up the value of the cache first. This only works
	with side-effect free functions of course.
@timeout
	Check if the execution time of a function exceeds a timeout
	limit. If so raise an exception.
@ignoreexceptions

In my opinion, you should avoid using decorators in productive code, if 
you don't have a good reason to do otherwise. Every decorator adds some 
sort of "magic" to your program and using too much "magic" will make it 
difficult to maintain.

- Patrick



More information about the Tutor mailing list