On 06/06/2018 03:51 PM, Nick Coghlan wrote:
On 6 June 2018 at 15:31, Rob Cliffe via Python-Dev <email@example.com mailto:firstname.lastname@example.org> wrote: ... *In other words, it looks as if in Python 3.6.5, the compiled list comprehension** **can "see" a pre-existing global variable but not a local one.*
Yes, this is expected behaviour - the two-namespace form of exec (which is what you get implicitly when you use it inside a function body) is similar to a class body, and hence nested functions (including the implicit ones created for comprehensions) can't see the top level local variables.
In issue 13557  Amaury gives the following explanation by quoting the documentation  "Free variables are not resolved in the nearest enclosing namespace, but in the global namespace" and hints at the same solution that is proposed by Nick.
FWIW in issue 21161  folks have been bitten by this when trying to run a list comprehension in pdb.