Sobes.tech
Junior

How can we determine that an object is an iterator?

sobes.tech AI

Answer from AI

You can check for the presence of __iter__ and __next__ methods. An object is an iterator if it implements the __next__ method. An object is iterable if it implements the __iter__ method. An iterator is a subtype of iterable.

Alternatively, you can use the isinstance function and abstract base classes from the collections.abc module.

from collections.abc import Iterator, Iterable

# Check if an object is an iterator
isinstance(some_object, Iterator)

# Check if an object is iterable
isinstance(some_object, Iterable)

Example of creating an iterator:

class MyIterator:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self  # Iterator always returns itself in __iter__

    def __next__(self):
        if self.current < self.limit:
            value = self.current
            self.current += 1
            return value
        else:
            raise StopIteration

it = MyIterator(3)

# Usage examples
print(next(it)) # 0
print(next(it)) # 1
print(next(it)) # 2

try:
    next(it)
except StopIteration:
    print("Iteration finished")

Example of an iterable object:

class MyIterable:
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        return iter(self.data) # Return an iterator over internal data

obj = MyIterable([10, 20, 30])

# Using in a for loop (the for loop automatically calls iter())
for item in obj:
    print(item)
How can we determine that an object is an iterator… - sobes.tech