Python type hints: what should I use for a variable that can be any iterable?

99 Views Asked by At

Consider the function:

def mysum(x)->int:
    s = 0
    for i in x:
        s += i
    return s

The argument x can be list[int] or set[int], it can also be d.keys() where d is a dict, it can be range(10), as well as any other iterable, where the item is of type int. What is the correct type-hint for x?

My python is 3.10+.

1

There are 1 best solutions below

4
e-motta On BEST ANSWER

You can use typing.Iterable:

from typing import Iterable

def mysum(x: Iterable[int]) -> int:
    s = 0
    for i in x:
        s += i
    return s

Edit: typing.Iterable is an alias for collections.abc.Iterable, so you should use that instead, as suggested in the comments.