0

I have the following code, and I wonder how I can prevent getting error.

class A:
    ...:     class Numbers(Enum):
    ...:         ONE = 1
    ...:         TWO = 2
    ...:     ODDS = (Numbers.ONE,)
    ...:     EVENS = [number for number in Numbers if not number in ODDS]

After running this snippet, I get NameError: name 'ODDS' is not defined.

Then I try to use ODDS as A.ODDS

In [71]: class A:
    ...:     class Numbers(Enum):
    ...:         ONE = 1
    ...:         TWO = 2
    ...:     ODDS = (Numbers.ONE,)
    ...:     EVENS = [number for number in Numbers if not number in A.ODDS]
    ...: 

In [72]: A.EVENS
Out[72]: [<Numbers.ONE: 1>, <Numbers.TWO: 2>]

However, I only want evens.. So if I try like this, the following happens.

In [76]: class A:
    ...:     class Numbers(Enum):
    ...:         ONE = 1
    ...:         TWO = 2
    ...:     ODDS = (Numbers.ONE,)
    ...:     EVENS = [number for number in A.Numbers if not number in A.ODDS]
    ...: 

In [77]: A.EVENS
Out[77]: [<Numbers.TWO: 2>]

Anyone knows why the last way work and previous ones do not?

Thanks

EDIT:

I restarted the shell and tried again

In [4]: class A:
   ...:     class Numbers(Enum):
   ...:         ONE = 1
   ...:         TWO = 2
   ...:     ODDS = (Numbers.ONE,)
   ...:     EVENS = [number for number in A.Numbers if not number in A.ODDS]

got NameError: name 'A' is not defined

Burakhan Aksoy
  • 319
  • 3
  • 14

1 Answers1

0

So I found this question on stackoverflow: Accessing class variables from a list comprehension in the class definition

here, the accepted answer details this pretty nicely. to summarize

So, to summarize: you cannot access the class scope from functions, list comprehensions or generator expressions enclosed in that scope; they act as if that scope does not exist. In Python 2, list comprehensions were implemented using a shortcut, but in Python 3 they got their own function scope (as they should have had all along) and thus your example breaks.

Burakhan Aksoy
  • 319
  • 3
  • 14