pythonmultidimensional-arrayclass-attributes

Python failed to initialize a 2d array as class attributes


I am implementing a transition tables as a class attribute with,

class Phase:
    num_states = 15
    transition_table = [[False for _ in range(num_states)] for _ in range(num_states)]

but it failed with NameError: name 'num_states' is not defined. However, 1d array works as expected,

class Phase:
    num_states = 15
    transition_table = [False for _ in range(num_states)] # this works

I was wondering why this is the case, as num_states is defined before transition_table and it should have access to the previous one?

Edit: this is due to Python's implement of class scopes; Use class attribs in outer scope for loop will not give an error, but inner scope will. There is a link in the comment that explains this in detail.


Solution

  • It looks like num_states is out of scope from the class definition. You can workaround this by passing the class variable into a lambda and run the list comprehension inside the lambda

    class Phase:
        num_states = 15
        transition_table = (lambda x=num_states: [[False for _ in range(x)] for _ in range(x)])()