decorators tutorials

Josiah Carlson josiah.carlson at sbcglobal.net
Wed Jul 25 02:42:15 EDT 2007


james_027 wrote:
> hi bruno,
> 
> That seems to be hard to read at all, or I am just very new to python?

No, it's hard to read.  Note that it's not, technically, necessary to 
use nested functions to get the same results as a particular decorator. 
  For example, earlier you provided...

def check_login(func):
     def _check_login(*args):
         print "I am decorator"
         return func(*args)
     return _check_login

That could be written as...

class check_login:
     def __init__(self, func):
         self.func = func
     def __call__(self, *args):
         print "I am decorator"
         return self.func(*args)

The latter class-based method is a bit clunkier, but I find that it's 
easier to understand and unravel after the fact (you can also add your 
own __repr__ method for useful introspection).


> With that decorator how do I take advantage of it compare when I just
> write a function that could do the same as what the decorator did? I
> could translate the could from above into ...
> 
> def check_login(msg):
>    #...
> def my_func(toto, tata):
>    #...
> 
> #call it like this
> check_login('msg')
> my_func('toto', 'tata')

There are many uses for decorators (I'm sure others have posted about 
them already), and really, the syntax is a convenience meant to reduce 
the number of times you need to type the same string...

@long_decorator
def realy_long_function_name():
     ...

rather than...

def realy_long_function_name():
     ...
realy_long_function_name = long_decorator(realy_long_function_name)


I try to limit my use of decorators whenever possible, both because I 
still have to support Python 2.3 (which doesn't support the syntax), and 
because I find that they obfuscate what the code is doing more often 
than not.  I will admit that they are useful as a metaprogramming 
technique.  Just be careful.

  - Josiah



More information about the Python-list mailing list