Skip to content

Instantly share code, notes, and snippets.

@benwei
Created July 3, 2012 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benwei/3040483 to your computer and use it in GitHub Desktop.
Save benwei/3040483 to your computer and use it in GitHub Desktop.
closure sample h4
# reference:
# http://stackoverflow.com/questions/3190706/nonlocal-keyword-in-python-2-x
# http://en.wikipedia.org/wiki/Closure_(computer_science)#Example
#
def counter():
d = {'x': 0} # tested with python 2.7.2
def increment(y=1):
# nonlocal only work for python3
#nonlocal x
d['x'] += y
return d['x']
return increment
def counter_by_dic_v2():
d = {'x': 0} # work with python 2.7.2
def increment(y=1):
return d.update({'x': d['x'] + y}) or d['x']
return increment
counter1_increment = counter() # counter() returns a closure containing a
# reference to the function increment()
# and increment()'s non-local variable x
counter2_increment = counter() # a second closure, containing a second
# instance of the variable x
counter3_increment = counter_by_dic_v2()
print 'dic v1'
print counter1_increment() # prints 1
print counter1_increment(7) # prints 8
print counter1_increment() # prints 9
print 'dic v1 second'
print counter2_increment() # prints 1
print counter2_increment() # prints 2
print 'dic v2'
print counter3_increment() # prints 1
print counter3_increment() # prints 2
print '==========<lambda>============================================================'
# one line lambda from Thinker Li
count=(lambda: lambda x=[0]: x.append(x[0] + 1) or (x.pop(0) and 0) or x[0])()
# one line lambda with dic
count_d=(lambda: lambda d={'x':0}: d.update({'x': d['x'] + 1}) or d['x'])()
# convert one line lambda to meaningful code
def count_inc():
x = [0] # tested with python 2.7.1+
def inc(init=1):
x.append(x[0] + init)
x.pop(0)
return x[0]
return inc
counter = count_inc()
print "lambda version"
print count(); # 1
print count(); # 2
print count(); # 3
print "meaningful version"
print counter(); # 1
print counter(); # 2
print counter(); # 3
print "lambda dic version"
print count_d(); # 1
print count_d(); # 2
print count_d(); # 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment