collections.Iterable vs typing.Iterable in type annotation and checking for Iterable

Question:

I found that in Python both collections.Iterable and typing.Iterable can be used in type annotation and checking for whether an object is iterable, i.e., both isinstance(obj, collections.Iterable) and isinstance(obj, typing.Iterable) works. My question is, what are the differences among them? And which one is preferred in which situations?

Asked By: Benjamin Du

||

Answers:

Due to PEP 585 – Type Hinting Generics In Standard Collections, Python’s standard library container types are also 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 is deprecated.

For older Python versions:

The typing.Iterable is generic, so you can say what it’s 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 doesn’t 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 don’t behave exactly the same way in all cases. You really don’t need generics at runtime, so there’s 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.

Answered By: gilch