简体   繁体   中英

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() ?

There is no catch. The typing library uses stubs from the collections library. You are totally allowed to use isinstance with the typing library, certainly for the types you mentioned (Mapping and Sequence).

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 (ie no interesting argument annotation) both seem equivalent to me, though abc may be the more usual tool for this.

As of python 3.9, the entire suite of collections.abc aliases in the typing module is deprecated , meaning that your preferred option for python >=3.9 should be to use the versions in the collections.abc module. The classes will not be removed from the typing module for a few years to come, however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM