Message 389595 - Python tracker

This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Content
Hmm yes, some more words in the documentation might help.

Does anyone understand why it happens, though?

Specifically, note that

sum(get(i) for i in range(len(l)))

or

eval("get(0) + get(1) + get(2) + get(3)")

or

eval("sum(get(i) for i in range(len(l)))", locals())

work just fine, but

eval("sum(get(i) for i in range(len(l)))")

fails, which is really confusing. I have no mental model of what is happening that allows for the first thing to work, but disallows for the second thing. I understand it has something to do with the creation of a new subscope when the comprehension is run, but other than that, I don't really understand.

Also, ideally, the last thing should work, too.

I am teaching programming to college students and I could not explain to them why the first three worked but the last one failed. There was simply nothing I could say that would give them a good mental model for the execution.