Skip to content

Instantly share code, notes, and snippets.

@pybites
Created November 17, 2020 15:58
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 pybites/1ae8b5f60bad232d2621673ad666d745 to your computer and use it in GitHub Desktop.
Save pybites/1ae8b5f60bad232d2621673ad666d745 to your computer and use it in GitHub Desktop.
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