简体   繁体   English

解释locals()及其工作原理

[英]Explain locals() and exactly how it works

Could someone please explain how this little piece of code works? 有人可以解释一下这小段代码如何工作吗?

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

I am assuming, and please correct me if I am wrong, but it gets all the variables in the current function and puts them in the dict and removes self and the dict it got put in, correct? 我是假设的人,如果我错了,请纠正我,但是它会获取当前函数中的所有变量,然后将它们放在dict中,并删除self和它放入的dict,对吗? Is there anything other than self and the dict I might not want going into there? 除了自我和我可能不想去的字典,还有别的吗?

Would there be anything wrong with just JSON serializing that dict and posting it? 仅用JSON序列化该字典并将其发布会有什么问题吗?

This probably comes from the Django template and the locals trick . 这可能来自Django模板和本地技巧 The idea is to populate a number of variables inside a function, and use locals() to pass them on to a template. 这个想法是在函数内部填充多个变量,然后使用locals()将它们传递给模板。 It saves the effort of creating a new dictionary with all those variables. 它节省了使用所有这些变量创建新字典的工作。

Specifically, your code creates a dictionary of all the local variables and removes self (the class object parameter) and info (the variable that was just created). 具体来说,您的代码创建了所有局部变量的字典,并删除了self (类对象参数)和info (刚刚创建的变量)。 All other local variables are returned. 返回所有其他局部变量。

You could then JSON serialize the data, as long as the data can be serialized. 然后,只要可以序列化数据,就可以对数据进行JSON序列化。 DateTime variables must be converted to a string first, for example. 例如,必须先将DateTime变量转换为字符串。

The code creates a new dictionary called 'info' and assigns all of your local python variables to it. 该代码创建了一个名为'info'的新字典,并将所有本地python变量分配给它。 NOTE: These are pointers to the same objects in your local environment, so that if you modify a list or dictionary in info it will be changed in your environment as well (this may or may not be the desired behavior). 注意:这些是指向同一个对象在本地环境,因此,如果您修改列表或字典info将在您的环境中也改变了(这可能是也可能不是所期望的行为)。

locals() Update and return a dictionary representing the current local symbol table. locals()更新并返回代表当前本地符号表的字典。 Free variables are returned by locals() when it is called in function blocks, but not in class blocks. 当在功能块中调用免费变量时,它是由locals()返回的,而不是在类块中调用。

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) and info.pop('info', None) will remove 'self' and 'info', respectively, from your new info dictionary. info.pop('self', None)info.pop('info', None)将从您的新info字典中分别删除'self'和'info'。 If they are not present, they return None . 如果不存在,则返回None Note that info.pop('self') would return a KeyError if 'self' was not in the dictionary. 请注意,如果字典中未info.pop('self')info.pop('self')将返回info.pop('self')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM