Sobes.tech
Junior — Middle

What is the role of special methods (dunder) in implementing generators and their use in Python?

sobes.tech AI

Answer from AI

In Python, special methods (dunder methods), such as __iter__(), __next__(), play a key role in implementing generators and iterators.

Generators are objects that allow iteration over a sequence of values, computing them on demand rather than all at once.

  • __iter__() returns the iterator object (often itself).
  • __next__() returns the next element in the sequence or raises the StopIteration exception when the elements are exhausted.

When you create a generator using a function with the yield keyword, Python automatically creates a generator object with these methods.

Example of implementing a simple iterator using dunder methods:

class CountUpTo:
    def __init__(self, max):
        self.max = max
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.max:
            raise StopIteration
        self.current += 1
        return self.current

for number in CountUpTo(3):
    print(number)

Thus, dunder methods provide the iteration protocol that underpins generators and allows their use in loops and other constructs working with iterable objects.

What is the role of special methods (dunder) in… - sobes.tech