-1

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

Llopeth
  • 406
  • 5
  • 11
  • 1
    it doesn't work this way even in normal function. At start it copy value from `willremove` to `remove` and later it doesn't use `willremove`. It can works only with content of list or dictionary because it will copy reference to list or dictionary and you can change value in list/dict outside `tempdir` and you get this value inside `tempdir`. OR you may have to use `willremove` directly in `tempdir`. – furas Jun 27 '19 at 11:02

1 Answers1

0

This cannot be done because the parameters in python are passed 'by assignment', as pointed by Ned Batchelder in the following talk:

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

Llopeth
  • 406
  • 5
  • 11