解释 locals() 及其工作原理

Explain locals() and exactly how it works

谁能解释一下这段代码是如何工作的?

info = {}
info.update(locals())
info.pop('self', None)
info.pop('info', None)

我假设,如果我错了请纠正我,但它获取当前函数中的所有变量并将它们放入 dict 并删除 self 和它放入的 dict,对吗?除了 self 和 dict 之外,还有什么我可能不想进入的吗?

只是 JSON 序列化该字典并发布它会有什么问题吗?

这可能来自Django template and the locals trick。这个想法是在一个函数中填充一些变量,然后使用 locals() 将它们传递给模板。它省去了使用所有这些变量创建新字典的工作。

具体来说,您的代码创建了一个包含所有局部变量的字典并删除了 self(class 对象参数)和 info(刚刚创建的变量)。返回所有其他局部变量。

然后您可以 JSON 序列化数据,只要数据可以序列化即可。例如,DateTime 变量必须先转换为字符串。

该代码创建了一个名为 'info' 的新字典,并将所有本地 python 变量分配给它。注意:这些是指向本地环境中相同对象的指针,因此如果您修改 info 中的列表或字典,它也会在您的环境中发生更改(这可能是也可能不是所需的行为)。

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.

info.pop('self', None)info.pop('info', None) 将分别从您的新 info 词典中删除 'self' 和 'info'。如果它们不存在,则它们 return None。请注意,如果 'self' 不在字典中,info.pop('self') 将 return 出现 KeyError。