What the Comprehension Can See

class Deck:
    ranks = [2, 3, 4]
    doubled = [r * 2 for r in ranks]

class Deck2:
    multiplier = 2
    ranks = [2, 3, 4]
    doubled = [r * multiplier for r in ranks]

One of these two class bodies raises NameError when the module is loaded. Which, and why?

A

Both raise NameError, because list comprehensions can never reference any name defined earlier in the same class body.

B

Deck2 raises NameError on multiplier: it is only referenced inside the comprehension's own scope, which cannot see class-body names, while Deck.ranks works because it is the outermost for's iterable, evaluated eagerly in the class body itself before that inner scope exists.

C

Deck raises NameError on ranks, since a comprehension's own scope can never see any name from its enclosing class body, including the iterable it loops over.

D

Neither raises: comprehensions always run inside the enclosing class body's own namespace, so both ranks and multiplier resolve normally.