I'm often in the need of temporarily switching the value of a variable out with something else, do some computation which depends on this variable, and then restore the variable to its original value. E.g:
var = 0
# Assign temporary value and do computation
var_ori = var
var = 1
do_something_with_var() # Function that reads the module level var variable
# Reassign original value
var = var_ori
This seems like an obvious opportunity for using a context manager (the with
statement). Does the Python standard library contain any such context manager?
I am aware that this sort of thing is most often handled by other, better means than temporarily changing a variable. I am however not asking for obvious workarounds.
In my actual work case, I can not alter the do_something_with_var
function. Actually this is not even a function, but a string of code which gets evaluated in the context of the global namespace as part of some metaprogramming. The example I gave was the simplest I could think of that kept my problem with the temporary variable. I did not ask to get a workaround (proper version) of my example code, but rather to get an answer on my written question.
Nope, because a context manager can't assign variables in the caller's scope like that. (Anyone who thinks you could do it with locals
or inspect
, try using the context manager you come up with inside a function. It won't work.)
There are utilities for doing that with things that aren't local variables, such as module globals, other object attributes, and dicts... but they're unittest.mock.patch
and its related functions, so you should strongly consider other alternatives before using them in a non-testing context. Operations like "temporarily modify this thing and then restore it" tend to lead to confusing code, and may indicate you're using too much global state.