locals
()Update and return a dictionary representing the current local symbol table. Free variables are returned by
locals()
when it is called in function blocks, but not in class blocks.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.
内置函数locals返回的是当前状态的本地命名空间, 应该当作只读字典处理, 写入会有意外发生.
在函数中, 或者其他局部变量产生的情况下, 对其的更改可能无法保存.
def f(): x = 10 lc = locals() lc['x'] = 20 # 'x'->20 remains on dictionary before locals() is called print lc # {'x': 20} locals() # locals dictionary is refreshed in the above call to locals() print lc # {'x': 10, 'lc': {...}} f()