Temporarily rebind an attribute using contextmanager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from __future__ import with_statement
from contextlib import contextmanager
@contextmanager
def redirect(object_, attr, value):
orig = getattr(object_, attr)
setattr(object_, attr, value)
yield
setattr(object_, attr, orig)
if __name__ == "__main__":
import sys
with redirect(sys, 'stdout', open('stdout', 'w')):
print "hello"
print "we're back"
|
Initially, I wanted to redirect stdout in a block. Later I realized this this is just an example of a more general useful pattern of rebinding an attribute of an object.
Tags: shortcuts