Quicker way of type hinting Iterable

Many functions expect parameters that are iterable and do not care if they are actually lists. But, instead of importing typing.Iterable, one may be tempted to just use list[type] and call it a day.

Like list can be made generic in a type hint, why not allow me to use iter like that as well?

Instead of:

from typing import Iterable

def go(a: Iterable[int]) -> None:
    for i in a:

You can write:

def go(a: iter[int]) -> None: # or aiter[int]!
    for i in a:

# we could go even further for sync iterables?
def go(a: [int]) -> None:
    for i in a:

I like it.

But one snag is that iter returns iterators, specifically. Thus, using it to type hint any kind of iterable is a little dubious. The analogy with list isn’t quite 1:1.

Semantically iter doesn’t make sense. This is a method, an instance of <class 'builtin_function_or_method'>. You want the type hint to be the name of a type. list[int] and Iterable[int] make sense.

Sounds great. But i’m not sure it always works.

@gooseontheloose you should join this new idea. READ ALL THE INFORMATION slowly

Because iter isn’t a type. What next, hex to mean a string that is prefixed with 0x and otherwise contains only hexadecimal digit symbols?

We’ve talked about this before (and similarly, about making builtins.callable[...] mean Callable. But as the other posts in this thread call out, the analogy just isn’t that good.

To add to what’s already been said, it’s going to be unclear to users whether iter[T] means Iterable[T] or Iterator[T].


If you don’t already, you should be using an editor that has an auto-import feature so that when you type Iterable, it always you automatically add the line

from collections.abc import Iterable

Neovim, for example, does this.