Python 3.4 provides this neat tool for temporarily redirecting stdout:
with redirect_stdout(sys.stderr):
help(pow)
The code is not too complicated, but I would not want to write it again and again, especially since some thoughts went into it to make it a repeated participant:
class redirect_stdout:
def __init__(self, new_target):
self._new_target = new_target
self._old_targets = []
def __enter__(self):
self._old_targets.append(sys.stdout)
sys.stdout = self._new_target
return self._new_target
def __exit__(self, exctype, excinst, exctb):
sys.stdout = self._old_targets.pop()
I am wondering if there is a general way to use the operator withto temporarily change the value of a variable. Two other use cases from sys: sys.stderrand sys.excepthook.
In an ideal world, something like this would work:
foo = 10
with 20 as foo:
print(foo)
print (foo)
I doubt that we can do this work, but maybe something like this is possible:
foo = 10
with temporary_set('foo', 20):
print(foo)
print (foo)
I can somehow make it work by rooting in globals(), but it will not want to be used by anyone.
: , "foo = 10" , , . :
- stderr, redirect_stdout
- sys.excepthook. , - excepthook ( , , ), , - . . .