Understanding Python closure

>> def create_multipliers():
…     return [lambda x : i * x for i in range(5)]

>>> for multiplier in create_multipliers():
…   print multiplier.__closure__[0].cell_contents

4
4
4
4
4

> def create_multipliers():
…    result = [lambda x : i * x for i in range(5)]
…    for fun in result:
…       print fun.__closure__[0].cell_contents

>>> create_multipliers()
4
4
4
4
4

>> def create_multipliers():
…    result=[]
…    for i in range(5):
…       result.append(lambda x: i*x)
…       print result[i].__closure__[0].cell_contents

>>>
>>> create_multipliers()
0
1
2
3
4
>>>

http://code.activestate.com/recipes/502271/

A CLOSURE is a function object that remembers values in enclosing scopes regardless of whether those scopes are still present in memory. If you have ever written a function that returned another function, you probably may have used closures even without knowing about them.

so only if a function is trying to access a variable form an enclosing scope, it is called a closure. http://stackoverflow.com/questions/4020419/why-arent-python-nested-functions-called-closures

http://www.shutupandship.com/2012/01/python-closures-explained.html

 

 

 

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s