pythonpython-typingiterable

Type Hint for finite iterable


My function foo accepts an argument things which is turned into a list internally.

def foo(things):
    things = list(things)
    # more code

The list constructor accepts any iterable.

However, annotating things with typing.Iterable does not give the user a clue that the iterable must be finite, not something like itertools.count().

What's the correct type hint to use in this case?


Solution

  • I am not aware of any possible way to achieve this in Python as you cannot provide such constraints in type hints.


    However, probably the Collection type might be useful in your context as a workaround:

    class collections.abc.Collection

    ABC for sized iterable container classes.

    This requires objects to have a __len__, which is a more strict requirement than being finite. For example, finite generators don't count as Collection.