1

I guess all Python generators are iterators.But all iterators are not generators.

So, given an iterable some_list how do I verify if it's a generator too (lazily evaluated)?

this doesn't work

>>> from csv import DictReader
>>> import types
>>> d = DictReader("file")
>>> isinstance(d,types.GeneratorType)
False

But my understanding is that DictReader is actually a generator

tobias_k
  • 81,265
  • 12
  • 120
  • 179
binithb
  • 1,910
  • 4
  • 23
  • 44
  • Not sure if that's possible at all, given how Python and duck typing etc. work. E.g., the top answers I've tried in the linked duplicate identify generators (`def` with `yield` or `(...)`), but return `False` on `range` or file handles. – tobias_k Nov 27 '19 at 16:04
  • Most things in Python are lazily evaluated. Why do you need to check that? If they aren't, either algorithm doesn't allow for it, or whoever wrote it is still writing in Python 2 mindset. –  Nov 27 '19 at 16:10
  • @Sahsahae what if a library returns me a list, but before using it I want to check if it's generator ( to do the processing more carefully if it's not a generator) – binithb Nov 27 '19 at 16:13
  • 1
    You do that by reading documentation of the library. If documentation is poor you probably shouldn't be using said library anyway, because Python itself can barely help you figure out what goes wrong when it does go wrong and thus the most work to ensure that intent is clear goes on the shoulders or whoever is supposed to document it. –  Nov 27 '19 at 16:19
  • @Sahsahae not even the documentation of DictReader in stdlib doesn't say if it's a generator or not – binithb Nov 27 '19 at 16:22
  • I don't know what documentation you are reading, but it clearly has stated that it does support the typical iterator protocol and that's all you need to know. –  Nov 27 '19 at 16:25
  • I was looking at the source of DictReader class https://github.com/python/cpython/blob/master/Lib/csv.py#L80. And the question is how to know if an iterable is a generator or not ( not just an iterator). I have already mentioned the usecase where that is useful( and similar reasons are mentioned also in the duplicated question). Thanks for your comments – binithb Nov 27 '19 at 16:34
  • I guess you could reword your question in a way that you are not necessarily looking for a way to do this _in code_. Might get un-duped then. – tobias_k Nov 27 '19 at 16:36
  • 2
    About the example of `DictReader`: Once we are at inspecting the code, a pretty clear hint that this is working lazily is that most of the code is in `__next__`. – tobias_k Nov 27 '19 at 16:37

0 Answers0