I am trying to modify on the fly some of the parameters used by the exit function of a context manager. I am trying to bind the parameter to a variable known in the with block
from contextlib import contextmanager
import tempfile, shutil
@contextmanager
def tempdir(suffix = '', prefix = '', dir = None, ignore_errors = False,
remove = True):
"""
Context manager to generate a temporary directory with write permissions.
"""
d = tempfile.mkdtemp(suffix, prefix, dir)
try:
yield d
finally:
print "finalizing tempdir %s, remove= %s" %(d,remove)
if remove:
shutil.rmtree(d, ignore_errors)
willremove = True
with tempdir(remove = willremove) as t:
#attempt to modify parameter
willremove = False
print "willremove:%s" %willremove
pass
I would expect that changing the value of willremove would change the remove variable in the finally: part of the contextmanager function, but it doesn't help