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}
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).