Temporarily changing a variable's value in Python

I know this question is kind of old, but as I came around the same problem, here is my solution:

class test_context_manager():
    def __init__(self, old_object, new_object):
        self.new = new_object
        self.old = old_object
        self.old_code = eval(old_object)
    def __enter__(self):
        globals()[self.old] = self.new
    def __exit__(self, type, value, traceback):
        globals()[self.old] = self.old_code

It's not pretty as it makes heavy use of global variables, but it seems to work.

For example:

x = 5
print(x)
with test_context_manager("x", 7):
    print(x)

print(x)

Result:

5
7
5

or with functions:

def func1():
    print("hi")

def func2():
    print("bye")

x = 5
func1()
with test_context_manager("func1", func2):
    func1()

func1()

Result:

hi
bye
hi

Building on the answer by @arthaigo, a more concise version is:

import contextlib

@contextlib.contextmanager
def temporary_assignment(object, new_value):
  old_value = eval(object)
  globals()[object] = new_value
  yield
  globals()[object] = old_value