3

I am trying to create a board for a game using list comprehension as shown in the code below.

class Game:
    row_num = 7
    column_num = 6
    board = [['[]' for i in range(row_num)] for x in range(column_num)]

However, when I run this I get: NameError: name 'row_num' is not defined. I've heard that list comprehension has their own namespace so I defined row_num as global as shown below.

class Game:
    global row_num
    row_num = 7
    column_num = 6
    board = [['[]' for i in range(row_num)] for x in range(column_num)]

This works fine, but my question is why doesn't python have a problem with the column_num variable? It is still in the same list comprehension so should have the same namespace as row_num?

rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
yerdeth
  • 51
  • 4
  • 2
    this.. is unconventional. I've never seen a `global` statement within a class body itself. – rv.kvetch Oct 01 '22 at 01:14
  • 1
    I would move up the first two vars to the module level, then you could simplify it a bit to `board = [['[]'] * row_num for _ in range(column_num)]`. – rv.kvetch Oct 01 '22 at 01:16
  • 1
    [This answer](https://stackoverflow.com/a/13913933/) goes into deep details about the scoping issue that's actually at play involving class scopes. Moreover, using the `global` keyword on `row_num` there basically moves `row_num` to the global (module) scope, see [example](https://stackoverflow.com/a/48920918/). – metatoaster Oct 01 '22 at 01:20
  • 2
    Also, note that in your second example, the `Game` class will no longer have a `Game.row_num` attribute. – metatoaster Oct 01 '22 at 01:27

0 Answers0