Search code examples
pythonpython-3.xtype-hinting

Correct type hinting for next() function and generators


Just playing around with understanding type hinting in python using PyCharm, and came across the following:

def range_iter(self, val: int):
    yield from range(val)

range_itterable = range_iter(10)

# Type hinting reports that next() returns a 'range'
type(next(range_itterable)) # but actual returned type is 'int'

What's the way to make the type hinting system happy here?


Solution

  • In your code, the type hint for range_iter() suggests it returns a range, but it actually returns integers from the range function. My bet is this is confusing Pycharm.

    You can specify the actual return type, which is an iterable of integers. Use from typing import Iterator and specify Iterator[int] as the return type.

    from typing import Iterator
    
    def range_iter(val: int) -> Iterator[int]:
        yield from range(val)
    
    range_iterable = range_iter(10)
    
    # Type hinting reports that next() returns an 'int'
    type(next(range_iterable))  # returns 'int'