0

On my version of Python (version info below), the following breaks at the line that assigns the variable e (but works just fine up until that point):

class Foo:
  a = 1
  b = a + 2
  print(b) # works
  c = [ "apple", "banana", "cherry", "dragonfruit" ]
  d = [ "I like " + fruit for fruit in c]
  print(d) # works
  d2 = c + ["elderberry"]
  print(d2) # works
  e = ["I like " + c[i] for i in range(4)] #ERROR: NameError: name 'c' is not defined
  print(e)

This surprises me; I can't tell whether this is intended behavior or a bug in Python. If this is intentional, can someone explain the intent?

From what I've seen, the problem only occurs in the context of static class variables. In other words, of course, if I replace "class Foo" with "if True" then the whole thing works without an error.

I'm using the following version of Python on OS-X 10.9.5: Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)

Alexander
  • 105,104
  • 32
  • 201
  • 196
  • Have you tried `e = ["I like" + x for x in c]`? – Brobin Jul 27 '15 at 18:38
  • Incidentally, this code doesn't produce an error in Python 2.7. Probably because they changed the scoping rules for list comprehensions so that the iterating variable wouldn't leak any more. – Kevin Jul 27 '15 at 18:39
  • 2
    Code produces error in Python 3.x only, because list comprehension has a different scope in Python 3.x . – Anand S Kumar Jul 27 '15 at 18:39
  • http://stackoverflow.com/questions/22797782/scope-of-class-variable-with-list-comprehension – Mazdak Jul 27 '15 at 18:40

0 Answers0