1

When I need to print variables, I tend to be lazy and use "{someVariable}".format( **locals() ) a lot. For example:

x = 10
[ "{x} {i}".format( **locals() ) for i in xrange(3) ]

Out:

['10 0', '10 1', '10 2']

But now if I use a generator instead:

x = 10
for y in ( "{x} {i}".format( **locals() ) for i in xrange(3) ) :
    print y

Out:

KeyError: 'x'

Oh no! What happened?

usual me
  • 8,338
  • 10
  • 52
  • 95
  • My answer on the dupe explains why; generators are run in a separate scope. In Python 2.7 list comprehensions don't, in Python 3 they too are run in a separate scope. – Martijn Pieters Jul 15 '14 at 08:53
  • In other words, `x` is not a local in a generator expression, it is instead either a closure or a global. – Martijn Pieters Jul 15 '14 at 08:54

0 Answers0