21.01.2015 Views

color version - PET: Python Entre Todos - Python Argentina

color version - PET: Python Entre Todos - Python Argentina

color version - 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.

id(greeting)<br />

3068236156L<br />

>>> greeting.__name__<br />

'greeting'<br />

>>> say_hello = greeting<br />

>>> say_hello()<br />

hello<br />

Decorator (non-strict definition)<br />

Let’s take a liberty for a moment and say that a decorator is a function d that receives as<br />

parameter another function a and returns a new function r.<br />

Code<br />

def d(a):<br />

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

print "Start of execution of", a.__name__<br />

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

print "End of execution of", a.__name__<br />

return r<br />

When executing a decorated function with the above decorator, a bit of text will be<br />

shown, then the decorated function will be executed and more text will appear as it<br />

finishes.<br />

In sum2 we keep the decorated <strong>version</strong> of sum. Now see what happens when we execute<br />

it:<br />

• d: function decorator<br />

• a: function to decorate<br />

• r: function decorated<br />

We can apply the decorator using a functional notation:<br />

a = d(a)<br />

Let’s see how to implement a generic decorator:<br />

Code<br />

def d(a):<br />

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

# a's previous execution behavior<br />

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

# a's after execution behavior<br />

return r<br />

We define a function d, our decorator, and in its body is defined a new function r, that<br />

we are going to return. In the body of r a is going to be executed, the decorated function.<br />

Now change the comments for code that actually does something:<br />

Manipulating functions<br />

def sum(a, b):<br />

print a + b<br />

>>> sum(1,2)<br />

3<br />

>>> sum2 = d(sum)<br />

>>> sum2(1,2)<br />

Start of execution of sum<br />

3<br />

Stop of execution of sum<br />

>>> sum = d(sum)<br />

>>> sum(1, 2)<br />

Start of execution of sum<br />

3<br />

Stop of execution of sum<br />

Also we can keep directly in sum the decorated <strong>version</strong> of sum and now the original<br />

<strong>version</strong> will not be longer accessible.<br />

Previous way of applying a decorator is the functional form. We have a nicer one:<br />

Syntactic sugar<br />

As of <strong>Python</strong> 2.4 the @ notation was incorporated for function decorators.

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

Saved successfully!

Ooh no, something went wrong!