Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
closure-example.py
# from Fluent Python 2nd ed
class Averager():
def __init__(self):
self.series = []
def __call__(self, new_value):
self.series.append(new_value)
total = sum(self.series)
return total/len(self.series)
def make_averager():
# closure, variable still available after local scope gone
# a function "closes over" any objects it maintains a reference to those objects
# https://stackoverflow.com/a/13902
count = 0 # immutable type > oops!
series = [] # mutable type no issue
def averager(new_value):
# without using nonlocal on count, you'd get an exception here:
# UnboundLocalError: local variable referenced before assignment
# because you try to assign a value to a local variable before it has been declared.
nonlocal count
count += 1
series.append(new_value)
total = sum(series)
return total/len(series)
return averager
if __name__ == '__main__':
avg = Averager()
print(avg(10), avg(11), avg(12))
avg2 = make_averager()
print(avg2(10), avg2(11), avg2(12))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment