A4 portrait - PET: Python Entre Todos - Python Argentina
A4 portrait - PET: Python Entre Todos - Python Argentina
A4 portrait - PET: Python Entre Todos - Python Argentina
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Decorator functions without arguments 30<br />
)<br />
return wrap<br />
@disable<br />
def yes(string='y', end='\n'):<br />
[...]<br />
Decorator functions without arguments<br />
In a decorator function that doesn’t receive arguments, its first and only parameter is<br />
the callable to be decorated. In the nested function is where decorated callable<br />
positional and keyword arguments are received.<br />
This can be seen in any of previous examples.<br />
Decorator functions with arguments<br />
Now we’ll look an example of a decorator function that receives arguments. The<br />
example will be based on our previous log_callable and will allow us to specify if we<br />
really want to count the number of calls.<br />
log_callable with arguments example:<br />
def log_callable(do_count):<br />
if not getattr(log_callable, 'count_dict', None) and do_count:<br />
log_callable.count_dict = {}<br />
if do_count:<br />
log_callable.count_dict.setdefault(<br />
callable.__name__, 0<br />
)<br />
def wrap(callable):<br />
def inner_wrap(*args, **kwargs):<br />
callable(*args, **kwargs)<br />
message = []<br />
if do_count:<br />
log_callable.count_dict.setdefault(<br />
callable.__name__, 0<br />
)<br />
log_callable.count_dict[callable.__name__] += 1<br />
message.append(<br />
u"""called: '{0}' '{1} times'""".format(<br />
callable.__name__,<br />
log_callable.count_dict[callable.__name__],<br />
)<br />
)<br />
else:<br />
message.append(u"""called: '{0}'""".format(callable.__name__))<br />
message.append(u"""Arguments: {0}""".format(", ".join(args)))<br />
message.append(<br />
u"""Keyword Arguments: {0}""".format(<br />
", ".join(["{0}={1}".format(key, value) \<br />
for (key, value) in kwargs.items()])<br />
)<br />
)<br />
logging.debug("; ".join(message))<br />
<strong>PET</strong>: English Translation (Issue 1, August 2010) — http://revista.python.org.ar