Python Forum
Why there is not __break__ dunder method
Poll: Did you think a __break__ dunder could be usefull
You do not have permission to vote in this poll.
Yes
50.00%
1 50.00%
No
50.00%
1 50.00%
Total 2 vote(s) 100%
* You voted for this item. [Show Results]

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why there is not __break__ dunder method
#4
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.
Reply


Messages In This Thread
RE: Why there is not __break__ dunder method - by Gribouillis - May-13-2023, 08:20 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020