修改 globals() 的输出是否安全?
locals() 函数的文档 特别警告不要修改其输出,因为解释器可能无法反映本地范围的变化。我假设这意味着 Python 规范不需要它,即使它可以在 CPython 中工作。
我想知道这对于 globals() 是否相同。 文档中没有警告,但我觉得很奇怪,这会不同之处在于每个函数显然在不同的范围内执行相同的操作。
如果安全的话,修改 globals()' 输出将提高我正在处理的项目的简单性和兼容性。
The documentation for the locals() function specifically warns not to modify its output, as interpreters may not reflect changes in the local scope. I'm assuming that means the Python spec doesn't require it, even though it works in CPython.
I'd like to know if this is the same for globals(). There's no warning in the documentation, but I find it strange that this would differ as each function apparently performs the same action on a different scope.
If it's safe, modifying globals()' output would improve the simplicity and compatibility of a project I'm working on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
即使在 CPython 中,修改
locals()
也无法可靠地工作。它恰好在模块和类作用域中工作,但在函数内部失败(任何修改“都不会发生”,因为locals()
在这种情况下提供了本地命名空间的副本,而不是对真实事物的引用)但是,
globals()
是不同的,因为总是引用模块名称空间,并且模块名称空间需要像普通字典一样运行。所以,是的,缺少对 globals() 的警告并不是疏忽,这确实是允许的。Modifying
locals()
doesn't work reliably, even in CPython. It happens to work in module and class scopes, but it fails inside a function (any modifications "won't take", sincelocals()
provides a copy of the local namespace in that case, rather than a reference to the real thing)However,
globals()
is different, since that always refers to the module namespace, and module namespaces are required to behave like ordinary dictionaries. So yes, the lack of a warning onglobals()
isn't an oversight, it really is allowed.