How to use collections.abc from both Python 3.8+ and Python 2.7

后端 未结 4 1822
执念已碎
执念已碎 2020-12-06 04:08

In Python 3.3 \"abstract base classes\" in collections (like MutableMapping or MutableSequence) were moved to second-level module

4条回答
  •  醉话见心
    2020-12-06 04:29

    Place this at the top of the script:

    import collections
    
    try:
        collectionsAbc = collections.abc
    except AttributeError:
        collectionsAbc = collections
    

    Then change all prefixes of the abstract base types, e.g. change collections.abc.MutableMapping or collections.MutableMapping to collectionsAbc.MutableMapping.

    Alternatively, import what you require in the script at the top in a single place:

    try:
        from collections.abc import Callable  # noqa
    except ImportError:
        from collections import Callable  # noqa
    

提交回复
热议问题