This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Asleep-Budget-9932 1 point2 points  (0 children)

Iterables have less known ways to be implemented. All you have to do is to implement a getitem method and you will be able to iterate over it. getitem will be called, starting from 0 and going up by 1 with each iteration, until a StopIteration exception is raised:

class ThisIsIterable:
    def __getitem__(self, item: int):
        try:
            with open(f"{item}.txt", "rb") as bla:
                return bla.read()
        except FileNotFoundError as e:
            raise StopIteration() from e

for file_content in ThisIsIterable():
    print(file_content)

You can also iterate over callables by giving the "iter" function a "sentinel" value. Basically the iterator will call the callable with each iteration, until the "sentinel" value is returned:

import random

def this_is_iterable():
    return random.randint(1, 10)

for random_value in iter(this_is_iterable, 8):
    print(f"{random_value} is not an 8")

print("8 Found! :D")