1

In some educational purposes I want to work with function's frame from "inspect" module. I want to change the value of local var outer the function. I get the frame of this function and tried to change its value, but nothing is happened.

Why? Here's the simpled code:

from inspect import getouterframes, currentframe

def foo():
    frame_of_main = getouterframes(currentframe())
    frame_of_main[1][0].f_locals['var'] = 1
    print(frame_of_main[1][0].f_locals['var'])


def main():
    var = 1337
    foo()


main()

outputs: 1337

As you can see, the value of var in the frame hasn't changed. What's going on?

macsash03
  • 19
  • 2

1 Answers1

1

A frame's f_locals is the same dict returned by the locals function inside that frame. The warning from the locals docs also applies to f_locals:

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

user2357112
  • 260,549
  • 28
  • 431
  • 505