Python locals()函数

原文: https://thepythonguru.com/python-builtin-functions/locals/


于 2020 年 1 月 7 日更新


locals()函数返回一个字典,其中包含在本地名称空间中定义的变量。 在全局名称空间中调用locals()与调用globals()相同,并返回代表模块全局名称空间的字典。

其语法如下:

  1. locals() -> dictionary containg local scope variables

这是一个例子:

  1. #!/usr/bin/python3
  2. from pprint import pprint
  3. a = 10
  4. b = 20
  5. def foo():
  6. x = 30 # x and y are local variables
  7. y = 40
  8. print("locals() = {0}".format(locals()))
  9. pprint(locals()) # same as calling globals()
  10. print('*' * 80)
  11. print("locals() == globals()? ", locals() == globals())
  12. print('*' * 80)
  13. foo()

预期输出

  1. {'__builtins__': <module 'builtins' (built-in)>,
  2. '__cached__': None,
  3. '__doc__': None,
  4. '__file__': 'module1.py',
  5. '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fa18790a828>,
  6. '__name__': '__main__',
  7. '__package__': None,
  8. '__spec__': None,
  9. 'a': 10,
  10. 'b': 20,
  11. 'foo': <function foo at 0x7fa1878752f0>,
  12. 'pprint': <function pprint at 0x7fa1878756a8>}
  13. ********************************************************************************
  14. locals() == globals()? True
  15. ********************************************************************************
  16. locals() = {'y': 40, 'x': 30}

试试看:

  1. from pprint import pprint
  2. a = 10
  3. b = 20
  4. def foo():
  5. x = 30 # x and y are local variables
  6. y = 40
  7. print("locals() = {0}".format(locals()))
  8. pprint(locals()) # same as calling globals()
  9. print('*' * 80)
  10. print("locals() == globals()? ", locals() == globals())
  11. print('*' * 80)
  12. foo()