Home >Backend Development >Python Tutorial >Python built-in function locals
English documentation:
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.
Explanation :
1. The function returns a dictionary consisting of local variables in the current scope and their values, similar to the globals function (returning global variables)
>>> locals() {'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None} >>> a = 1 >>> locals() # 多了一个key为a值为1的项 {'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'a': 1, '__doc__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}
2. Can be used within functions.
>>> def f(): print('before define a ') print(locals()) #作用域内无变量 a = 1 print('after define a') print(locals()) #作用域内有一个a变量,值为1 >>> f <function f at 0x03D40588> >>> f() before define a {} after define a {'a': 1}
3. The returned dictionary set cannot be modified.
>>> def f(): print('before define a ') print(locals()) # 作用域内无变量 a = 1 print('after define a') print(locals()) # 作用域内有一个a变量,值为1 b = locals() print('b["a"]: ',b['a']) b['a'] = 2 # 修改b['a']值 print('change locals value') print('b["a"]: ',b['a']) print('a is ',a) # a的值未变 >>> f() before define a {} after define a {'a': 1} b["a"]: 1 change locals value b["a"]: 2 a is 1 >>>