0

This seems like a really weird scoping issue:

First I'll show what works:

class A():
   x = 1
   y = x

class B():
   x = {'a' : 1, 'b' : 2}
   y = {z : 1 for z in x}

Does not work:

class C():
   x = {'a' : 1, 'b' : 2}
   y = {z : max(x) for z in x}    #  max could be replaced with any function

Leading to:

NameError: name 'x' is not defined

And I know it refers to the "inner" (value) in the dictionary comprehension.

This probably means that somehow in the list comprehension the class scope is not available.

How come, and how can we work around this (without using it as an instance variable, i.e. using __init__)?

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
  • Or even not a function - `y = {z: x for z in x}` won't work either. See also http://stackoverflow.com/q/22692227/3001761 – jonrsharpe Feb 14 '15 at 23:48
  • I was aware that not using a function does not work, but I assume some people start complaining that it wouldnt make sense... Though nicely found! – PascalVKooten Feb 14 '15 at 23:52
  • The class scope is surely avaiable to a list-comprhension in Python 2, but not to other comprehensions. https://docs.python.org/2/reference/executionmodel.html#naming-and-binding – Ashwini Chaudhary Feb 14 '15 at 23:55

0 Answers0