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
#3
class SomeBoard:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.grid = [[0 for _ in range(width)] for _ in range(height)]
        self._iter_data: list[list] = []
    
    def __getitem__(self, co: tuple[int, int]):
        return self.grid[co[1]][co[0]]

    def __iter__(self):
        self._iter_data.append([-1, 0])
        return self

    def __next__(self):
        last = _iter_data[-1]
        last[0] += 1
        if last[0] == self.width:
            last[0] = 0
           last[1] += 1
            if last[1] == self.height:
                del self._iter_data[-1]
                raise StopIteration

        return last[0], last[1], self.grid[last[0], last[1]]

board = SomeBoard(8, 8)
# do something with it

for x, y, tile in board:
    break

print(board._iter_data)
The probleme is that i can't break when I iterate trough CustomBoard, because that will leave date inside _iter_data
with a __break__ dunder I could simply solve this by:
def __break__(self):
    del self._iter_data[-1]
And now the iterator will work properly

But if _iter_data were only made of one list containing the x and y coordinate then I couldn't iterate trough a CustomBoard instance like this:
board = CustomBoard(8, 8)
for x1, y1, tile1 in board:
    for x2, y2, tile2 in board:
        # do something 
        ...
The problem now is that this program will result in an endless loop
Reply


Messages In This Thread
RE: Why there is not __break__ dunder method - by Phidias618 - May-13-2023, 05:27 PM

Forum Jump:

User Panel Messages

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