Created
July 7, 2021 17:36
-
-
Save maxfischer2781/1c0dedba091986604c2c2b2130f069bf to your computer and use it in GitHub Desktop.
Use a context manager to average over several method calls
This file contains 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 contextlib import contextmanager | |
class Optimizer: | |
def __init__(self, weight: int): | |
self.weight = weight | |
def step(self, num): | |
num = self.calculate(num) | |
return self.apply(num) | |
def calculate(self, num: int): | |
return num - self.weight | |
def apply(self, num: int): | |
self.weight = num % 10 | |
return num | |
@contextmanager | |
def average(opt: Optimizer): | |
storage = [] | |
def apply(num): | |
storage.append(num) | |
return num | |
old_apply = opt.apply | |
opt.apply = apply | |
try: | |
yield opt | |
finally: | |
opt.apply = old_apply | |
avg = sum(storage) / len(storage) | |
opt.apply(avg) | |
optimizer = Optimizer(3) | |
for _ in range(4): | |
with average(optimizer): | |
for _ in range(3): | |
print(optimizer.step(7)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment