python - 为什么在 locals 中添加 key 实际上会创建变量?

标签 python local

我尝试创建一个名称中带有空格的变量,我想出了这个:

>>> classic_var = 'spam'
>>> locals()['classic_var'] 
'spam'
>>> classic_var
'spam'
>>> locals()['local_var'] = 'eggs'
>>> locals()['local_var'] 
'eggs'
>>> local_var
'eggs'
>>> locals()['variable with space in names'] = 'parrot'
>>> locals()['variable with space in names']
'parrot'

但是有人回复了(source):

The dictionary returned by locals() just represents the entries in the local symbol table, these are not the symbols themselves. So changing this dictionary does not create any variable at all. See here: https://docs.python.org/3/library/functions.html#locals

所以我想知道为什么会这样:

>>> a = 'test'
>>> locals()['a'] = 'hello'
>>> locals()['b'] = 'world'
>>> print(a, b)
hello world

在函数内部,局部变量修改不起作用,但使用 globals() 时,行为相同。

文档说:“更改可能不会影响解释器使用的局部变量和自由变量的值”。 “可能”。但条件是什么?为什么是“可能”?什么情况下?

这不是针对专业项目,只是研究 python 的工作原理以及我们如何调整事物来创造奇怪的东西。

最佳答案

如果您阅读实际文档,您将看到以下内容:

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.

文档没有 promise 修改字典会做什么。


locals()真的很奇怪。这不仅仅是更改字典对局部变量产生不一致的影响 - 更改局部变量字典产生不一致的影响。

在全局范围内,或在类语句中,字典 locals()返回是本地范围的实际规范表示。更改字典将更改该范围内的变量,而分配变量将更改字典。

在函数作用域,字典 locals()返回不是本地范围的主要表示。它是附加到堆栈框架的单独字典。调用locals()使用局部变量的当前值更新该字典并返回该字典。

在函数作用域,更改字典通常不会更新局部变量,但在某些特殊情况下(主要与调试相关),Python 会将值从字典复制回局部变量。

在函数作用域,更改局部变量通常不会更新字典,除非您调用 locals()再次或某些东西访问框架对象的 f_locals属性。调试器访问f_locals读取局部变量值,因此使用 locals() 的代码如果调试器没有编写来处理此问题,通常会中断调试器:

>>> def f():
...     x = 1
...     y = locals()
...     x = 2
...     print(y['x'])
... 
>>> f()
1
>>> def f():
...     x = 1
...     y = locals()
...     x = 2
...     breakpoint()
...     print(y['x'])
... 
>>> f()
> <stdin>(6)f()
(Pdb) n
2

在这里,添加断点会导致函数打印 2而不是1 .

关于python - 为什么在 locals 中添加 key 实际上会创建变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71467179/

相关文章:

具有上下文管理器的 Python mixin 无法正确解决 "super"调用

css - Magento local.xml 引用名称 ="head"到根目录中的 addItem

javascript - 页面重新加载后从本地存储中检索复选框集合的保存状态

perl - "Turn Off"binmode(STDOUT, ":utf8") 本地

Python .pop() 全局更改本地列表?

python - 在 Python 3.4 中导入表格时出现问题

Python:在 pandas 中读取 #0000000000 格式的 Excel 列时如何保留前导零

python - Neo4j 如何在 python 中访问节点的属性

c++ - 整理哈希函数

python - 如何使用python打印随机森林回归中重要特征的顺序?