[Tutor] Writing decorators?
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Jul 5 19:06:49 EDT 2016
On 05/07/16 18:31, Alex Hall wrote:
> For decorators, do you never include parentheses except for passing
> arguments? It seems a bit odd to drop them if they'd be empty, given that
> anywhere else doing so would return the function object rather than call
> it.
Remember what the @ sign is doing.
@decorator
def func():...
is effectively suyntactic sugar for
func = decorator(func)
If you write @decorator()
That translates to
@decorator()(func)
which is not at all the same thing.
Of course you could get into brain melting mode and
write a meta-decorator that returns a decorator!
>>> def meta():
def decorator(f):
def logit(*args,**kwargs):
print("called function with ", args, kwargs)
return f(*args,**kwargs)
return logit
return decorator
>>> @meta() #with parens and potentially args
def square(x): return x*x
>>> square(3)
called function with (3,) {}
9
>>>
yikes! It all starts to get too complicated for my tiny
brain at this point and I usually find another more
explicit way to do what I need...
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list