decorators tutorials
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Jul 23 06:26:13 EDT 2007
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