Treats a list as a generator with an optional additional generator. This is used for macro replacement for example.

class cpip.util.ListGen.ListAsGenerator(theList, theGen=None)

Class that takes a list and provides a generator on that list. If the list is exhausted and call for another object is made then it is pulled of the generator (if available).

The attribute listIsEmpty is True if the immediate list is empty.

Iterating through the result and stopping when the list is exhausted using the flag listIsEmpty:

To be clear: when this flag is set, for example if we have a list [0,1,2,3] followed by [‘A’, ‘B’, ‘C’] thus:

myObj = ListAsGenerator(range(3), ListAsGenerator(list('ABC')).next())

And we try to iterate over it with list comprehension:

myGen =
myResult = [x for x in myGen if not myObj.listIsEmpty]

myResult will be [0, 1,] because when 3 is yielded the flag is False as it refers to the _next_ item.

Similarly the list comprehension:

myResult = [x for x in myGen if myObj.listIsEmpty]

Will be [3, ‘A’, ‘B’, ‘C’]

If you want to recover the then this the technique:

myResult = []
if not myObj.listIsEmpty:
    for aVal in myGen:
        if myObj.listIsEmpty:

Or exclude the list then this the technique:

if not myObj.listIsEmpty:
    for aVal in myGen:
        if myObj.listIsEmpty:
myResult = [x for x in myGen]

The rationale for this behaviour is for generating macro replacement tokens in that the list contains tokens for re-examination and the last token may turn out to be a function like macro that needs the generator to (possibly) complete the expansion. Once that last token has been re-examined we do not want to consume any more tokens than necessary.


True if the next yield would come from the generator, not the list.


yield the next value. The attribute listIsEmpty will be set True immediately before yielding the last value.

Previous topic


Next topic


This Page