为什么在python中修改本地人不是个好主意? [英] Why is it bad idea to modify locals in python?
问题描述
与该回复相关的此处.
Related to this reply here. Locals' doc here.
文档提到字典不应更改,不确定其含义,但是locals()
是否适用于数据不会更改的实验室报告,例如在测量中?
The docs mention that the dictionary should not change, not sure what it means but would locals()
be applicable in lab-reports where data won't change, for example in measurements?
推荐答案
修改是一个坏主意,因为文档(您链接到该文档)明确表示不:
Modification is a bad idea because the documentation (which you link) explicitly says not to:
注意:请勿修改此词典的内容;更改可能不会影响解释器使用的局部变量和自由变量的值.
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.
除了这些,您不需要任何其他原因.
You don't need any more reason than that.
如果您以不修改任何变量的方式使用它,那么您会没事的,但是我会质疑设计,看看是否有更好的方法来做您想要的事情.
If you are using it in a way that doesn't modify any variables, then you'll be fine, but I'd question the design and see if there's a better way to do what you want.
在您链接的特定示例中,当在模块的全局范围内使用locals时,locals实际上是globals().这种非常具体的用法现在可以使用,尽管我希望它可以像全局变量一样继续使用,但您最好也可以使用全局变量.
In the specific example you link, locals is actually globals(), as you use it in the global scope of a module. This very specific use works now and, though I expect it to continue to work just as with globals, you might as well just use globals instead.
一个更干净的解决方案可能是在不知道其余设计的情况下,对变量使用常规的ol'字典;然后使用data ["x"] =值,而不是globals()["x"] =值.
An even cleaner solution is probably, without knowing the rest of your design, to use a regular ol' dictionary for your variables; then use data["x"] = value instead of globals()["x"] = value.
这篇关于为什么在python中修改本地人不是个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!