4 ms·
What would be the corresponding context manager for the summing example, where you use the square function and the inverse (the square root) ? Context managers
by rtpg 11y ago
What would be the corresponding context manager for the summing example, where you use the square function and the inverse (the square root) ?
Context managers works well for files (or general relations on objects really) but less for more abstract operations, I've found.
- b0sk 11y agoIt's ugly import math def sqr(x): return x*x class VecMag: def __init__(self, comp): self.comp = comp def __enter__(self): self.comp = map(sqr, self.comp) return self def __exit__(self, type, value, traceback): print math.sqrt(self.mag) def sum(self): self.mag = sum(self.comp) comp = (1,2,3,4) with VecMag(comp) as squared: squared.sum() $python test.py 5.47722557505