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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Ingredients 28<br />

In this article i’m going to write about how to code decorators in our favourite<br />

language.<br />

A decorator is basically a callable 1 that wraps another and which allows us to modify<br />

the behavior of the wrapped one. This might sound complicated at the beginning but<br />

it is really easier than it seems.<br />

Now, without any further ado we are going to cook some tasty home-baked wrapped<br />

callables.<br />

Ingredients<br />

• a callable<br />

• a decorator<br />

• coffee (optional)<br />

• sugar (opcional)<br />

Our to-be-wrapped callable for example will look like this:<br />

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

"""outputs `string`.<br />

This is similar to what the unix command `yes` does.<br />

Default value for `string` is 'y'<br />

"""<br />

print(string, sep='', end=end)<br />

Our decorator used to wrap the callable looks like this:<br />

def log_callable(callable):<br />

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

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

"""<br />

if not getattr(log_callable, 'count_dict', None):<br />

log_callable.count_dict = {}<br />

log_callable.count_dict.setdefault(<br />

callable.__name__, 0<br />

)<br />

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

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

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

message = []<br />

message.append(<br />

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

callable.__name__,<br />

log_callable.count_dict[callable.__name__]<br />

)<br />

)<br />

message.append(<br />

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

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

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