Python built-in functions (39) -- locals, pythonlocals
English document:
locals()
Update and return a dictionary representing the current local symbol table. Free variables are returnedlocals()When it is called in function blocks, but not in class blocks.
Note:
1. The function returns a dictionary composed of local variables and their values in the current scope, 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 () # An additional item {'_ package _': None, '_ loader _': <class '_ frozen_importlib.BuiltinImporter'> with a key of 1, 'A': 1, '_ doc _': None, '_ name _': '_ main _', '_ builtins __': <module 'builtins '(built-in)>,' _ spec _ ': None}
2. It can be used in functions.
>>> Def f (): print ('before define A') print (locals () # No variable a = 1 print ('after define A') in the scope ') print (locals () # There is a variable a in the scope. The value is 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 () # No variable a = 1 print ('after define A') in the scope ') print (locals () # There is a variable a in the scope. The value is 1 B = locals () print ('B ["a"]:', B ['a']) B ['a'] = 2 # modify B ['a'] value print ('change locals value ') print ('B ["a"]:', B ['a']) print ('A', a) # The value of a has not changed >>> f () before define a {} after define a {'A': 1} B ["a"]: 1 change locals valueb ["a"]: 2a is 1 >>>