30.11.2014 Views

A4 portrait - PET: Python Entre Todos - Python Argentina

A4 portrait - PET: Python Entre Todos - Python Argentina

A4 portrait - PET: Python Entre Todos - Python Argentina

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Decorator classes with arguments 32<br />

)<br />

logging.debug("; ".join(message))<br />

In a decorator class that doesn’t receive parameters, the first param of __init__<br />

method is the callable to be decorated. The __call__ method receives the arguments<br />

of the decorated callable.<br />

The most interesting difference with the function version is that by using a class<br />

decorator we have avoided the need of a nested function.<br />

The way to use this decorator is the same as we do with decorator functions:<br />

@LogCallable<br />

def yes(string='y', end='\n'):<br />

[...]<br />

Decorator classes with arguments<br />

Understanding the 3 previous cases it is possible to guess how a decorator class with<br />

arguments should be.<br />

LogCallable with params example:<br />

class LogCallable(object):<br />

"""Decorates callable and logs information about it.<br />

Logs how many times the callable was called and the params it had.<br />

"""<br />

def __init__(self, do_count):<br />

self.do_count = do_count<br />

if not getattr(LogCallable, 'count_dict', None) and do_count:<br />

LogCallable.count_dict = {}<br />

def __call__(self, callable):<br />

def wrap(*args, **kwargs):<br />

callable(*args, **kwargs)<br />

message = []<br />

if self.do_count:<br />

LogCallable.count_dict.setdefault(<br />

callable.__name__, 0<br />

)<br />

LogCallable.count_dict[callable.__name__] += 1<br />

message.append(<br />

u"""called: '{0}' '{1} times'""".format(<br />

callable.__name__,<br />

LogCallable.count_dict[callable.__name__],<br />

)<br />

)<br />

else:<br />

message.append(u"""called: '{0}'""".format(callable.__name__))<br />

message.append(<br />

u"""Arguments: {0}""".format(<br />

", ".join(map(str, args))<br />

)<br />

)<br />

message.append(<br />

u"""Keyword Arguments: {0}""".format(<br />

<strong>PET</strong>: English Translation (Issue 1, August 2010) — http://revista.python.org.ar

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!