如何修改with块中来自contextmanager的参数?

时间:2019-06-27 10:49:00

标签: python python-2.7 contextmanager

我正在尝试即时修改上下文管理器的退出功能所使用的某些参数。我试图将参数绑定到with块中已知的变量

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

我希望更改willremove的值会更改contextmanager函数的finally:部分中的remove变量,但这无济于事

1 个答案:

答案 0 :(得分:0)

无法完成此操作,因为Ned Batchelder在下面的演讲中指出,python中的参数是通过“赋值”传递的:

https://www.youtube.com/watch?v=_AEJHKGk9ns