This is filed as b.p.o. issue #21161, but closed as "won't fix".
The root issue is exactly what user2357112's answer says: Comprehensions1 work by defining and then running a hidden nested function, but functions defined in pdb inside a frame aren't real nested functions and can't access variables from the frame's scope.
There are workarounds (some of which are mentioned in the b.p.o issue, or places linked from that issue), but they're all just clever variations on one of these:
(lambda abc: [abc for _ in range(2)])(abc) (In other words, define a function and explicitly pass the locals' values as arguments instead of capturing them.)
[abc_ for abc_ in [abc] for _ in range(2)] (In other words, use the fact that the outermost iterable is an argument.2)
[loc['abc'] for loc in [locals()] for _ in range(2)] (In other words, use locals()['name'] instead of name, and get the locals passed as above.)
- Use
exec plus any of the known just-as-horrible workarounds for comprehensions in exec.
- Don't use a comprehension, as user2357112 suggests.
1. In Python 2.x, this is not true for list comprehensions, only set and dict comprehensions and generator expressions. But Python 3 changed list comprehensions to make them consistent with the others.
2. The hidden nested function for a comprehension captures almost all names from the enclosing scope—but the outermost iterable (the one in the first for) is special; it's actually a parameter to the hidden function, and the expression is evaluated in the enclosing scope and passed as the argument value.
eval("(lambda: x)()", vars())