对dict理解中的locals()下标失败,并显示KeyError [英] Subscripting locals() in a dict comprehension fails with KeyError

查看:244
本文介绍了对dict理解中的locals()下标失败,并显示KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python locals()的奇怪行为感到困惑. 基本上我想从字典理解中的locals()字典中获取一个项目,但是失败了.这是非常基本的事情,所以:

I have been baffled by an odd behaviour of Python locals().
Basically I want to get an item from the dictionary of locals() in a dictionary comprehension, yet it fails. It is an extremely basic thing, so:

>>> foo=123
>>> bar=345
>>> baz=678
>>> {k: locals()[k] for k in ('foo','bar','baz')}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
KeyError: 'foo'
>>> locals()['foo']
123
>>> locale=locals()
>>> {k: locale[k] for k in ('foo','bar','baz')}
{'foo': 123, 'bar': 345, 'baz': 678}
>>> type(locals())
<class 'dict'>
>>> def fun():
...     return {'foo': 123,'bar':345}
... 
>>> {k: fun()[k] for k in ('foo','bar')}
{'foo': 123, 'bar': 345}

从实用的角度来看,字典或字符串.format()中较丑的{'foo':foo, 'bar': bar}等都可以正常工作.
只是我想念一些东西,所以知道为什么会增加我的编码能力(到目前为止,我在编码时不发光).

On a practical side the uglier {'foo':foo, 'bar': bar} etc. in dict or in string .format() works fine.
It is just that I am missing something so knowing why will increase my coding chi (as of now I don't glow when coding).

推荐答案

由于Python 3中的所有理解都是使用隐藏函数实现的,因此调用locals不会返回您期望它返回的值.

Because all comprehensions in Python 3 are implemented using a hidden function, calling locals doesn't return the values you're expecting it to return.

您可以通过将值打印出来来查看:

You can see this by printing the values out:

>>> _ = {k: print(locals()) for k in ('foo','bar','baz')}
{'k': 'foo', '.0': <tuple_iterator object at 0x7fdf840afa90>}
{'k': 'bar', '.0': <tuple_iterator object at 0x7fdf840afa90>}
{'k': 'baz', '.0': <tuple_iterator object at 0x7fdf840afa90>}

locals()分配给locale就像您所做的那样.您不是在理解内调用locals.

Assigning locals() to locale, as you do, takes care of this. You aren't calling locals inside the comprehension.

请注意,在Python 2中,情况有些模糊. dict-comps确实会以类似的方式失败,但是在dict-comps之前的list-comps可以正常工作:

Note that, in Python 2, the situation is a bit murkier. dict-comps do fail in a similar fashion but list-comps, which predate dict-comps, work just fine:

>>> _ = [locals()[k] for k in ('foo', 'bar', 'baz')]
>>> _
[20, 40, 60]

这是已解决与Py3.

这篇关于对dict理解中的locals()下标失败,并显示KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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