1

To my surprise, in Python 3 (but not 2), this code throws a NameError:

class Test:
    n = ["1"]
    [ n[i] for i in range(1) ]

gives

[ n[i] for i in range(1) ]
NameError: name 'n' is not defined

The problem is that the scope used to execute the n[i] is a new local scope and can't see the class variables (just like you couldn't see them in a function definition). But, according to the docs

The class’s suite is then executed in a new execution frame (see Naming and binding), using a newly created local namespace and the original global namespace

This seems to me to suggest that during the execution of the list comprehension expression the class variables should just look like variables in an enclosing scope and so be suitably accessible. But not so.

Python 3.7.2

What gives?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
strubbly
  • 3,347
  • 3
  • 24
  • 36
  • a workaround is `[i for i in n]`, that works – Jean-François Fabre Feb 22 '19 at 18:04
  • it's probably related to the list comprehension scoping change from 2 to 3. – Jean-François Fabre Feb 22 '19 at 18:07
  • 1
    "during the execution of the list comprehension expression the class variables should just look like variables in an enclosing scope" - they kinda do, but only enclosing *function* scopes are accessible for closure variable lookup. – user2357112 Feb 22 '19 at 18:10
  • 1
    This is the same reason you can't access class variables unqualified from methods of the class. – user2357112 Feb 22 '19 at 18:11
  • @user2357112 I can see why. This scope is special: it is going to be turned into a class dictionary. But the docs clearly say that at the time of execution of the class's suite it's just a normal execution frame. – strubbly Feb 22 '19 at 18:15
  • Ahh - the linked answer explains the place in the docs where it is explicitly stated that names in class blocks are not visible in enclosed scopes. So the compiler essentially deliberately prevents this so that we don't get into trouble when the frame is repurposed at the end of class definition. – strubbly Feb 22 '19 at 18:31

0 Answers0