Skip to content

Instantly share code, notes, and snippets.

@maxfischer2781
Created July 7, 2021 17:36
Show Gist options
  • Save maxfischer2781/1c0dedba091986604c2c2b2130f069bf to your computer and use it in GitHub Desktop.
Save maxfischer2781/1c0dedba091986604c2c2b2130f069bf to your computer and use it in GitHub Desktop.
Use a context manager to average over several method calls
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