Search code examples
pythonduck-typing

Python documentation: iterable many times?


In documenting a Python function, I find it more Pythonic to say:

def Foo(i):
    """i: An interable containing…"""

…rather than…

def Foo(i):
    """i: A list of …"""

When i really doesn't need to be a list. (Foo will happily operate on a set, tuple, etc.) The problem is generators. Generators typically only allow 1 iteration. Most functions are OK with generators or iterables that only allow a single pass, but some are not.

For those functions that cannot accept generators/things that can only be iterated once, is there a clear, consistent Python term to say "thing that can only be iterated more than once"?

The Python glossary for iterable and iterator seem to have a "once, but maybe more if you're lucky" definition.


Solution

  • I don't know of a standard term for this, at least not offhand, but I think "reusable iterable" would get the point across if you need a short phrase.

    In practice, it's generally possible to structure your function so that you don't need to iterate over i more than once. Alternatively, you can create a list out of the iterable and then iterate over the list as many times as you want; or you can use itertools.tee to get multiple independent "copies" of the iterator. That lets you accept a generator even if you do need to use it more than once.