pythongenerator

vobject.readcomponents(...) : Is it a generator or does it *return* a generator?


This is a question about technical terminology.

The vobject documentation says "readComponents is a generator", which is consistent with its doc string "Generate one Component at a time from a stream".

However, the sample code vobject.readComponents(icalstream).next().vevent.dtstart.value shows that readComponents(...) returns a generator, as does the example code here: for c in vobject.readComponents(vcfs):.

It makes a difference. Repeatedly invoking a method that returns a generator simply recreates the generator anew.

Is the reference to vobject.readComponents as a generator simply a case of speaking loosely, i.e., it actually returns a generator?

Afternote: I think my confusion arises from the fact that "The term generator in Python can refer to a generator iterator or a generator function. These are different but related objects in Python". Calling a generator multiple times returns independent generator iterators (a.k.a. generator objects). And of course, each iterator can only run through the elements once.


Solution

  • vobject.readcomponents is a generator, and it returns a generator iterator. Per the definition of "generator" in the Python glossary:

    A function which returns a generator iterator. It looks like a normal function except that it contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the next() function.

    Usually refers to a generator function, but may refer to a generator iterator in some contexts. In cases where the intended meaning isn’t clear, using the full terms avoids ambiguity.

    It's not very common for a module to contain generator iterators, so in documentation, it's safe to assume that "generator" refers to the function.