On 27 June 2018 at 08:52, Chris Angelico rosuav@gmail.com wrote:
On Wed, Jun 27, 2018 at 5:30 PM, Paul Moore p.f.moore@gmail.com wrote:
But test() returns [1, 2]. So does that say (as you claim above) that "the comprehension ran in the enclosing scope"? Doesn't it just say that the outermost iterable runs in the enclosing scope?
Yes - because the *outermost iterable* runs in the enclosing scope. But suppose you worded it like this:
def test(): a = 1 b = 2 vars = {key: locals()[key] for key in locals()} return vars
What would your intuition say? Should this be equivalent to dict(locals()) ?
As I said on python-list, my intuition doesn't apply to locals() - I simply have no idea what I'd "expect" from that code, other than a request to go back and write it more clearly :-)
*After* staring at it for a while and trying to interpret it base on the detailed knowledge I've gained from this thread, I'd say it does nothing remotely useful, and if you want dict(locals()) you should write it. (No, test() is not equivalent, because the two instances of locals() refer to different scopes, but I can't imagine why I'd ever need to know that outside of solving artificial puzzles like this).
Paul