4 ms·
Isn't what he's describing very similar to the "with" statement in Python? You can define a context manager to use with "with" that has methods that get execute
by greenyoda 11y ago
Isn't what he's describing very similar to the "with" statement in Python? You can define a context manager to use with "with" that has methods that get executed on the entry and exit of the "with" block, e.g., to open/close a file or acquire/release a lock.
- sumanthvepa 11y agoThat was exactly my thought. The pattern isn't new at all. C++ calls it RAII.
- rtpg 11y agoWhat 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
- baddox 11y agoLooks about right to me. And in Ruby, the same general pattern is implemented with blocks: File.open("foo.txt", 'w') {|f| f.write("bar")}
- deleted 11y ago[deleted]