import code def foo(): i = 3 print "Before: i = %r" % i interpreter = code.InteractiveInterpreter(locals()) line = "i = i + 4" interpreter.runsource(line, "") print "After: i = %r" % i foo() j = 4 interpreter = code.InteractiveInterpreter(locals()) line = "j = j + 3" interpreter.runsource(line, "") print "After: j = %r" % j