15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

count2 = counter(100)<br />

>>> print count2()<br />

101<br />

>>> print count()<br />

8<br />

The one difference is that we were able to do something that previously required us to write a class, and<br />

not only that, but to have to override the __call__() special method of that class to make its instances<br />

callable. Here we were able to do it with a pair of functions.<br />

Now, in many cases, a class is the right thing to use. Closures are more appropriate in cases whenever<br />

you need a callback that has to have its own scope, especially if it is something small and simple, and<br />

often, clever. As usual, if you use a closure, it is a good idea to comment your code and/or use doc<br />

strings to explain what you are doing.<br />

*Chasing Down Closure Lexical Variables<br />

The next two sections contain material for advanced readers ... feel free to skip it if you wish. We will<br />

discuss how you can track down free variables with a function's func_closure attribute. Here is a code<br />

snippet that demonstrates it.<br />

If we run this piece of code, we get the following output:<br />

no f1 closure vars<br />

f2 closure vars: ['']<br />

f3 closure vars: ['', '']<br />

<br />

<br />

<br />

<br />

Example 11.7. Tracking Closure Variables (closureVars.py)<br />

This example shows how we can track closure variables by using a function's func_closure<br />

variable.<br />

1 #!/usr/bin/env python<br />

2<br />

3 output = ''<br />

4 w = x = y = z = 1<br />

5<br />

6 def f1():<br />

7 x = y = z = 2<br />

8<br />

9 def f2():<br />

10 y = z = 3<br />

11<br />

12 def f3():<br />

13 z = 4

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

Saved successfully!

Ooh no, something went wrong!