python – collections.Iterable vs typing.Iterable in type annotation and checking for Iterable
typing.Iterable is generic, so you can say what its an iterable of in your type annotations, e.g.
Iterable[int] for an iterable of ints.
The collections iterable is an abstract base class. These can include extra mixin methods to make the interface easier to implement when you create your own subclasses.
Now it so happens that
Iterable doesnt include any of these mixins, but it is part of the interface of other abstract base classes that do.
Theoretically, the typing iterable works for either, but it uses some weird metaclass magic to do it, so they dont behave exactly the same way in all cases. You really dont need generics at runtime, so theres no need to ever use it outside of type annotations and such. The collections iterable is less likely to cause problems as a superclass.
So in short, you should use the typing iterable in type annotations, but the collections iterable as a superclass.
Due to PEP 585, as of version 3.9, Pythons standard library container types will also be able to accept a generic argument for type annotations. This includes the
collections.abc.Iterable class. When supporting only Python 3.9 or later, there is no longer any reason to use the
typing.Iterable at all and importing any of these container types from
typing will be deprecated.