Search code examples
pythonpython-itertools

itertools.islice is not a generator?


I have a code piece that works on generators and generator functions. When I try to slice the generators with itertools.islice, the code piece generates no outputs.

I've looked into the code, and found out the following code piece:

if isinstance(result, dict):
    self.returned(result)
elif inspect.isgenerator(result):
    for x in result:
        self.returned(x)
else:
    self.returned(result)

It turns out that inspect.isgenerator returns False for itertools.islice, which is what breaks the code. inspect.isgeneratorfunction behaves the same.

  1. Isn't itertools.islice a generator, or an generator function?
  2. How can I find out of result is a generator OR an itertools.islice object?

Solution

  • Based on

    inspect.getmembers(itertools.islice)
    

    islice is an iterator, not a generator. More info Difference between Python's Generators and Iterators