写到locals()的工作方式与文档相反,认为不行 [英] Writing to locals() works in contrast to documentation saying its not

查看:258
本文介绍了写到locals()的工作方式与文档相反,认为不行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在修改变量范围以及如何修改/复制它们,因为我想在IPython中动态地对一些结果进行后处理. 目前,对locals(),vars()和globals()的困惑对我来说是真实的. 特别是因为这段代码的输出:

I am currently tinkering with the variable scopes and how they can be modified / copied, as I would like to postprocess some results dynamically in IPython. The confusion about locals(), vars() and globals() is real for me right now. Especially because the output of this piece of code:

Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()["test"] = 5
>>> print(test)
5

根据不只是简短的文档,在我的理解中,这应该是不可能的:

According to the more than brief documentation this should not be possible in my understanding:

请注意,由于更新到 当地人字典将被忽略.

Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

(出于任何原因,

说明 vars()函数)

(which is for whatever reason stated in the description of the vars() function)

我希望有人能启发我:)

I hope someone can enlight me :)

推荐答案

您在哪里读这本书? Py 2文档

Where are you reading this? Both Py 2 docs and Py 3 docs have the following disclaimer:

注意:请勿修改此词典的内容;更改可能不会影响解释器使用的局部变量和自由变量的值.

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.

这准确地说明了这是什么:实现细节.当然,它可以在CPython中工作,但是可能无法在其他各种解释器中工作,例如IronPython和Jython.这就是所谓的hack.

This shows exactly what this is: an implementation detail. Sure, it works in CPython, but it might not work in the various other interpreters, like IronPython and Jython. It's what would be called a hack.

不要依赖它来更新任何变量.甚至不要尝试做任何严重的事情,因为它会导致不确定的行为.

Do not rely on it updating any variables. Do not even try to do it for anything serious, as it causes undefined behaviour.

在CPython 3.6.0中,help(locals)具有以下注释:

In CPython 3.6.0, help(locals) has the following note:

NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.

CPython 2.7.13却没有这样的注释.

CPython 2.7.13 has no such note, however.

这篇关于写到locals()的工作方式与文档相反,认为不行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆