Feb-13-2017, 04:52 AM
Couldn't you do this with a with block? The context manager you define can handle the "first" and "last", while the block is what gets executed in between?
>>> class Pipe: ... def __init__(self, start, end): ... self.start = start ... self.end = end ... def __enter__(self): ... self.start(self) ... return self ... def __exit__(self, *args): ... self.end(self) ... >>> def setup(pipe): ... pipe.counter = 0 ... >>> def teardown(pipe): ... print("final count: {0}".format(pipe.counter)) ... >>> with Pipe(setup, teardown) as p: ... for i in range(4): ... p.counter += i ... final count: 6