python中的locals()和globals()和dir()之间的区别

difference between locals() and globals() and dir() in python

假设此代码:

1
2
3
4
5
6
7
8
9
>>> iterator=filter(lambda x: x % 3 == 0, [2, 18, 9, 22, 17, 24, 8, 12, 27])
>>> x=int()
>>> locals()
{'__package__': None, '__spec__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'iterator': <filter object at 0x02E732B0>, 'x': 0, '__doc__': None}
>>> globals()
{'__package__': None, '__spec__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'iterator': <filter object at 0x02E732B0>, 'x': 0, '__doc__': None}
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'iterator', 'x']
>>>

locals,globals和dir有什么区别? 用法是什么?


在全局范围内,locals()globals()都将同一词典返回到全局名称空间。但是在函数内部,locals()将副本返回到本地名称空间,而globals()将返回全局名称空间(其中将包含全局名称)。因此,它们之间的区别仅在函数中可见。显示此的示例-

1
2
3
4
5
6
7
8
9
10
>>> locals() == globals() #global scope, that is directly within the script (not inside a function.
True
>>> def a():
...     l = 1
...     print('locals() :',locals())
...     print('globals() :',globals())
...
>>> a()
locals() : {'l': 1}
globals() : {'BOTTOM': 'bottom', 'PROJECTING': 'proj....

globals()的文档中-

globals()

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

locals()的文档中-

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.

为了回答有关用法的问题,一种用法是能够使用字符串来访问变量/名称。例如,如果您有一个名为a的变量,并且想使用字符串-'a'来访问其值,则可以将globals()locals()用作-globals()['a'],这将为您返回全局变量alocals()['a']的值将在当前名称空间中返回a的值(当直接位于脚本内部时为全局名称空间,如果位于函数内部则为本地名称空间)

dir()显示了作为参数传入的对象的属性列表,没有参数则返回当前本地名称空间中的名称列表(类似于locals()。keys())。从dir()的文档中-

dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.


如果尝试在函数中执行它们,您会注意到localsglobals之间的区别。如果尝试从控制台运行它们而不创建嵌套作用域,则明显的结果是您将不会注意到任何区别。

  • locals返回一个在本地范围内声明的变量字典:https://docs.python.org/2/library/functions.html#locals
  • globals返回一个在全局范围内声明的变量字典:https://docs.python.org/2/library/functions.html#globals
  • 如果不提供参数,则dir的工作方式与locals相似,但是如果将一个对象作为参数传递,则它将返回该对象的有效属性列表:https://docs.python .org等/ 2 /库/ functions.html#DIR


globals()返回具有(key, value)对的dict-对象中当前全局命名空间(当前模块+内置模块的范围)中的符号。 key是带有符号名称的字符串,而value是符号本身的值(例如数字1,另一个dict,函数,类等)。

locals()返回当前本地名称空间(功能范围)中的符号。在模块级别调用时,其结果与globals()相同。

dir()(不带参数)从当前本地名称空间返回名称列表。

在模块级别运行以下三个命令时,它们具有相同的值:

1
2
3
4
5
6
>>> sorted(locals().keys())
['A', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc']
>>> sorted(dir())
['A', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc']
>>> sorted(globals().keys())
['A', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc']

如果进行这三个调用,则函数locals().keys()dir()的值相同,但globals()不同。

1
2
3
4
5
6
7
8
9
>>> def A():
...   print(sorted(locals().keys()))
...   print(sorted(dir()))
...   print(sorted(globals().keys()))

>>> A()
[]
[]
['A', 'B', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc']

您可以看到使用globals()locals()的用法有所不同。

但是dir()呢?

dir()的要点是,它接受一个对象作为参数。它将返回该对象的属性名称的列表。您可以使用它,例如在运行时检查对象。

如果我们在上面的示例中使用函数A(),我们可以调用:

1
2
>>> dir(A)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

并获取功能对象a的所有属性。

关于dir()的更多详细信息,位于:Python中dir(...)和vars(...)。keys()之间的区别?


在全局范围内(例如在交互式提示符下),您的localsglobals是相同的。但是,在函数内部,它们是不同的:

1
2
3
4
5
6
7
8
9
10
11
x = 'some'
y = 'this'

def foo(x):
    y = 'that'
    print"My locals:", `locals()`
    print"My globals:", `globals()`

# locals has x: other and y: that only
# globals contains x: some, y: this and many more global names
foo('other')

值为'some'的全局变量x与值为'other'的局部变量x是不同的变量(对于名为y的两个变量来说也是相同的)。

查看内建文档以获取详细信息,或查看Python范围规则的文档。

不带参数的dir()本质上与locals().keys()相同(文档说:不带参数,返回当前本地范围内的名称列表。)