decorators tutorials

james_027 cai.haibin at gmail.com
Mon Jul 23 08:04:42 EDT 2007


hi bruno,

That seems to be hard to read at all, or I am just very new to python?

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')

Thanks
james
On Jul 23, 6:26 pm, Bruno Desthuilliers <bruno.
42.desthuilli... at wtf.websiteburo.oops.com> wrote:
> james_027 a écrit :
>
> > Hi all,
>
> > I am having difficulty understanding decorator. The definition was
> > clear for me, but the syntax is not so clear to me.
>
> > will decorators will always have to be in this way
>
> > def check_login(func):
> >     def _check_login(*args):
> >         print "I am decorator"
> >         return func(*args)
> >     return _check_login
>
> Sort of... Well, depends...
>
> Basically, a decorator is a callable taking a callable as argument and
> returning a callable. These callable are usually *but* not necessarily
> functions. You may want to read the section about the special method
> __call__ in the  Fine Manual.
>
> Also, you may want to write a 'parameterized' decorator - a decorator
> taking arguments. In this case, you need one more wrapping level:
>
> def check_login(msg):
>    def check_login_deco(func):
>      def _check_login(*args, **kw):
>        print msg
>        return func(*args, **kw)
>      return _check_login
>    return check_login_deco
>
> @check_login("I am the decorator")
> def my_func(toto, tata):
>    print toto, tata





More information about the Python-list mailing list