文档
In [4]: help(locals)
Help on built-in function locals in module builtins:
locals()
Return a dictionary containing the current scope's local variables.
返回当前 scope的 local variables,字典形式
NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
python 会维护在 symbol tables 中维护程序信息,它们有两种类型
- local symbol table 储存相关的程序的本地信息,使用 locals() 获取
- global symbol table 储存相关的程序的全局信息,使用blocals() 获取
symbol table 包含 variable name, methods, classes, etc
>>> a = locals()
>>> type(a)
<class 'dict'>
>>>
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': {...}}
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': {...}}
So where is the difference between locals() and globals()?
There is no difference because we are executing locals() and globals() in the current module itself. The difference will be present when we call these functions inside a method or class.
以上输出没有区别,因为都在当前模块中执行,scope 一样;如果在不同的函数或者方法中调用,结果会有不同。
In [1]: def add(a, b):
...: print(a, b)
...: print(locals())
...: return a+b
...:
In [2]:
In [2]: print(add(5, 4))
5 4
{'a': 5, 'b': 4}
9
python locals insde class
>>> class Data:
... x = 0
... print('locals value inside class\n', locals())
... print('globals value inside class\n', globals())
...
locals value inside class
{'__module__': '__main__', '__qualname__': 'Data', 'x': 0}
globals value inside class
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>>
>>>
作用
python locals 主要用于调试目的。我们可以检查本地范围中存在有哪些变量及值。我们也可以改变他们的值,因为它本质是一个字典(但是不推荐)