Skip to content
Advertisement

Should `isinstance()` check against typing or collections.abc?

Both typing and collections.abc includes similar type such as Mapping, Sequence, etc.

Based on the python documentation, it seems that collections.abc is preferred for type checking:

This module provides abstract base classes that can be used to test whether a class provides a particular interface; for example, whether it is hashable or whether it is a mapping. https://docs.python.org/3/library/collections.abc.html

but using typing also works and I’d rather not import Mapping from both typing and collections.abc. So is there any catch in using typing with isinstance()?

Advertisement

Answer

Many of the typing generic classes are just aliases to the abc ones. Just as an example from the docs, Hashable:

class typing.Hashable

An alias to collections.abc.Hashable

Also,

isinstance(abc.Hashable, typing.Hashable)
isinstance(typing.Hashable, abc.Hashable)

are both True, making it clear they are equivalent in terms of the class hierarchy. In Python you can check an alias’s origin using the origin field:

>>> typing.Hashable.__origin__
<class 'collections.abc.Hashable'>

No reason I can see to import abc if you do not need it. The two packages provide close but different uses, so I would import only what you need. This is more of an opinion, but if your use-case is only checking against isinstance (i.e. no interesting argument annotation) both seem equivalent to me, though abc may be the more usual tool for this.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement