Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an infinite for loop bad practice?

I'm implementing a card game in Python, and for my class to handle players, PlayerHandler, I recently implemented __next__ to simply call next_player. Because gameplay can be thought of in an infinite loop (The players will keep playing until they quit or win/lose), it did not make sense for it to stop iteration. However, it could seem confusing if a for loop caused an infinite loop, so should I raise a StopIteration somewhere?

class PlayerHandler():
    """Holds and handles players and order"""
    def __init__(self, players=None, order=1):
        if players is None:
            self.players = []
        else:
            self.players = list(players)
        self.current_player = None
        self.next_player()
        self.order = order

    def get_player(self, interval):
        assert type(interval) == int, "Key must be an integer!"
        if not interval and self.players:
            return self.current_player
        elif self.players:
            step = interval * self.order
            index = self.players.index(self.current_player) + step
            while index >= len(self.players):
                index -= len(self.players)
            while index <= -(len(self.players)):
                index += len(self.players)
            return self.players[index]
        else:
            raise KeyError("No players in the list!")

    def next_player(self):
        """Sets the current player to the next player to play"""
        if not self.current_player:
            if self.players:
                self.current_player = self.players[0]
            else:
                self.current_player = None
        else:
            self.current_player = self.get_player(1)

    def __iter__(self):
        return self

    def __next__(self):
        self.next_player()
        return self.current_player
like image 389
Timidger Avatar asked Oct 02 '22 00:10

Timidger


1 Answers

What matters is that your code is readable. If you're worried, add a comment -- that's what they're for!

# Endless loop
for p in players:
    # Do game things...

Having said that, maybe you should StopIteration when there are no more players.

like image 74
dwurf Avatar answered Oct 13 '22 10:10

dwurf