Context manager to temporarily change the variable of a register [aka write swap(a,b)]

Diez B. Roggisch deets at nospam.web.de
Wed Aug 26 09:33:26 CEST 2009


Evan Driscoll schrieb:
> On Aug 25, 3:47 pm, Evan Driscoll <eva... at gmail.com> wrote:
>> So here is my simplified version that only works for globals:
> 
> So I think this works if (1) you only use changed_value in the same
> module as it's defined in (otherwise it picks up the globals from the
> module it's defined in, which is almost certainly not what you want),
> and (2) the value you want to change is just a simple variable and not
> either something like "os.path" or a builtin.
> 
> I have worked on this a bit more and have something that addresses
> these issues in at least the cases I've tested. I'm not going to post
> the code here, but it is up at
>   http://pages.cs.wisc.edu/~driscoll/python/utils.py
> and there are a few unit tests at
>   http://pages.cs.wisc.edu/~driscoll/python/utils_test.py
> 
> I solved issue (1) by reintroducing the use of inspect to walk back up
> the stack a couple frames, but I pulled out the f_globals member
> instead of f_locals.
> 
> Issue (2a) I fixed by splitting the variable name at periods and
> walking through successive dictionaries with each component. Issue
> (2b) I fixed by looking for a '__builtins__' entry if the name I'm
> looking up doesn't exist.
> 
> Right now it's sort of hackish... it probably doesn't respond
> particularly well if things go unexpectedly (e.g. a bad variable name
> is given) and I should probably verify that the value is unchanged
> during the with statement and throw an exception otherwise, but it
> probably works well enough for my purposes for now.
> 
> Comments are appreciated... a couple of the things in there it seems
> like there could very well be reimplementations of things that are
> already done.


I'd still won't use it :) instead, something like this might be 
something I'd use, if I need a local "rebound". Or, again, just use a 
different *name* alltogether.

foo = "bar"


@apply
def f(foo="baz"):
     ...



Other than that, for your original use-case, I have a context-manager I 
call "safe modifier" that

  - takes an object, key and value
  - stores the old value of the key on the object
  - sets the new value
  - on exit, restores the old value

This is for e.g. temporary config-changes in tests.

Diez



More information about the Python-list mailing list