Skip to content

Instantly share code, notes, and snippets.

@TheProjectsGuy
Created August 3, 2022 11:48
Show Gist options
  • Save TheProjectsGuy/ea3f9b8d33dd4821b1e3f37f02f13751 to your computer and use it in GitHub Desktop.
Save TheProjectsGuy/ea3f9b8d33dd4821b1e3f37f02f13751 to your computer and use it in GitHub Desktop.
Testing (creating) custom python iterators using iter, next, or getitem
# Testing __getitem__() and Python Iterators
"""
Some resources:
- https://stackoverflow.com/a/61658447/5836037
"""
# %%
class Something:
def __init__(self) -> None:
self.items = [10, 20, 35, 60, 75]
self.ki = 0
def __getitem__(self, i):
return self.items[i]
def __iter__(self):
print(f"Iterator called, resetting 'ki'")
self.ki = 0
return self
def __next__(self):
if self.ki >= len(self.items):
raise StopIteration("Stop the iter")
ret = self.items[self.ki]
self.ki += 1
return ret
# %%
a = Something()
# %%
i = 0
for k in a:
print(k)
i += 1
if i > 20:
break
# %%
ai = iter(a)
while True:
print(next(ai))
# The last result should be a StopIteration exception
# %%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment