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

Evan Driscoll evaned at gmail.com
Wed Aug 26 01:51:42 CEST 2009


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.

Evan



More information about the Python-list mailing list