Created
November 17, 2020 15:58
-
-
Save pybites/1ae8b5f60bad232d2621673ad666d745 to your computer and use it in GitHub Desktop.
closure-example.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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