I love the decorator in Python!!!

88888 Dihedral dihedral88888 at googlemail.com
Fri Dec 9 19:21:11 EST 2011


On Saturday, December 10, 2011 2:28:49 AM UTC+8, 88888 Dihedral wrote:
> On Thursday, December 8, 2011 7:43:12 PM UTC+8, Chris Angelico wrote:
> > On Thu, Dec 8, 2011 at 10:22 PM, K.-Michael Aye <kmic... at gmail.com> wrote:
> > > I am still perplexed about decorators though, am happily using Python for
> > > many years without them, but maybe i am missing something?
> > > For example in the above case, if I want the names attached to each other
> > > with a comma, why wouldn't I just create a function doing exactly this? Why
> > > would I first write a single name generator and then decorate it so that I
> > > never can get single names anymore (this is the case, isn't it? Once
> > > decorated, I can not get the original behaviour of the function anymore.
> > 
> > The example given is a toy. It's hardly useful. However, there are a
> > number of handy uses for decorators; mostly, they consist of giving a
> > single simple keyword to a complicated set of logic. One example is
> > the @classmethod and @staticmethod decorators - the code to implement
> > them could be uglier than nested inline assembly, but you don't have
> > to care, because you just type "@staticmethod" in front of your def
> > statement and it does its magic.
> > 
> > Here's a handy trick that I'm sure someone has done in a more sophisticated way:
> > 
> > def trace(func):
> >     if debugmode:
> >         return lambda *a,**ka:
> > (print(">"+func.__name__),func(*a,**ka),print("<"+func.__name__))[1]
> >     return func
> > 
> > Then you put @trace in front of all your functions, and if debugmode
> > is False, nothing will be done - but set it to true, and you get
> > console output at the entry and exit of each function.
> > 
> > >>> @trace
> > def test(x):
> > 	print("Test! "+x)
> > 	return 5
> > 
> > >>> test("asdf")
> > >test
> > Test! asdf
> > <test
> > 5
> > 
> > Again, it's helpful because it condenses all the logic (including the
> > 'debugmode' flag) down to a single high level directive: "Trace this
> > function".
> > 
> > ChrisA
> 
> I did use decorators to turn functions into iterables to be traced.

It is easy to use decorators in python to mimic those programs in Erlang. 






More information about the Python-list mailing list