May-13-2023, 08:20 PM
I don't understand exactly what your code is doing but in complex cases, a good design is to create an iterator class separate from the class upon which you iterate. This iterator class will carry the data necessary to the iteration steps and also the specific code, so the structure could be
class SomeBoard: def __init__(self, width, height): self.width = width self.height = height self.grid = [[0 for _ in range(width)] for _ in range(height)] def __getitem__(self, co: tuple[int, int]): return self.grid[co[1]][co[0]] def __iter__(self): return BoardIterator(self) class BoardIterator: def __init__(self, board): self.board = board self._iter_data = [[-1, 0]] def __iter__(self): return self def __next__(self): ... # custom iteration code here board = SomeBoard(8, 8) # do something with it for x, y, tile in board: break print(board._iter_data)Note that the SomeBoard class has no
__next__
method here. A SomeBoard instance is iterable but it is not an iterator.