close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to use collections.abc from both Python 3.8+ and Python 2.7 in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    One way to solve this is to simply try to get abc from collections, else assume the members of abc are already in collections.

  2. use collections.abc from both Python 3.8+ and Python 2.7

    One way to solve this is to simply try to get abc from collections, else assume the members of abc are already in collections.

Method 1

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

Method 2

One way to solve this is to simply try to get abc from collections, else assume the members of abc are already in collections.

import collections                                         
collections_abc = getattr(collections, 'abc', collections)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read