Skip to content

Instantly share code, notes, and snippets.

@StephenFordham
Created June 5, 2020 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save StephenFordham/6d5a250bd2b721b6099ab650a481f1d5 to your computer and use it in GitHub Desktop.
Save StephenFordham/6d5a250bd2b721b6099ab650a481f1d5 to your computer and use it in GitHub Desktop.
custom_iterator_object
class CustomIterTeams(object):
def __init__(self, division, teams=[]):
self._mng = division
self._teams = teams
self._index = -1
def __iter__(self):
return self
# def __iter__(self):
# return (t for t in self._teams)
def __next__(self):
self._index += 1
if self._index >= len(self._teams):
self._index = -1
raise StopIteration
else:
return self._teams[self._index]
def __reversed__(self):
return self._teams[::-1]
prem_teams = CustomIterTeams('Premier League', ['Arsenal', 'Watford', 'Bournemouth', 'Man Utd', 'Liverpool'])
for t in prem_teams:
print(t)
@robinnarsinghranabhat
Copy link

robinnarsinghranabhat commented Jul 6, 2022

This is a buggy implementation.

Try doing this :

prem_teams = CustomIterTeams('Premier League', ['Arsenal', 'Watford', 'Bournemouth' ])
for t in prem_teams:
	break

# ===== PRINT STARTS FROM `Watford` and NOT `Arsenal` ===== #
for t in prem_teams:
	print(t)

SOLUTION :
This is the correct way to ensure that iterable object can be used multiple times.
https://stackoverflow.com/questions/21665485/how-to-make-a-custom-object-iterable

class BarIterator(object):
    def __init__(self, data_sequence):
        self.idx = 0
        self.data = data_sequence
    def __iter__(self):
        return self
    def __next__(self):
        self.idx += 1
        try:
            return self.data[self.idx-1]
        except IndexError:
            self.idx = 0
            raise StopIteration  # Done iterating.


class Bar(object):
    def __init__(self, data_sequence):
        self.data_sequence = data_sequence
    def __iter__(self):
        return BarIterator(self.data_sequence)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment