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?
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.
According to the non-goals in the PEP 484 documentation, type checking and performance optimization is dependent on third-party tools or left to the programmer. So in short: no, they will not cause any run-time effects, unless you explicitly make use of them.
Iterables, order, and mutability In Python, an iterable object (or simply an iterable) is a collection of elements that you can loop (or iterate) through one element at a time.
Type annotations — also known as type signatures — are used to indicate the datatypes of variables and input/outputs of functions and methods. In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype — the code will not run.
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.
Update:
Due to PEP 585, as of version 3.9, Python's 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With