pythonpython-typingmypypython-3.8

What type to use for itertools.count in Python?


I am trying to specify the type of an itertool.count object in Python, like so:

from itertools import count

c: count = count()

However, running mypy yields the following error:

test.py:3: error: Function "itertools.count" is not valid as a type
test.py:3: note: Perhaps you need "Callable[...]" or a callback protocol?
Found 1 error in 1 file (checked 1 source file)

It seems to be caused by the fact that itertools.count behaves like a function. However, it returns an itertools.count object, as shown by

In [1]: import itertools
In [2]: type(itertools.count()) is itertools.count
Out[2]: True

Then, how should I specify the type of the result of count() ?


Solution

  • There is following annotation in itertools.pyi:

    _N = TypeVar('_N', int, float)
    
    def count(start: _N = ...,
              step: _N = ...) -> Iterator[_N]: ...  # more general types?
    

    Thus, in your code, you could do like this:

    from typing import Iterator
    from itertools import count
    
    c: Iterator[int] = count()
    c_i: Iterator[int] = count(start=1, step=1)
    c_f: Iterator[float] = count(start=1.0, step=0.1)  # since python 3.1 float is allowed