Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In Python 3.3 "abstract base classes" in collections (like MutableMapping or MutableSequence) were moved to second-level module collections.abc. So in Python 3.3+ the real type is collections.abc.MutableMapping and so on. Documentation states that the old alias names (e.g. collections.MutableMapping) will be available up to Python 3.7 (currently the latest version), however in 3.8 these aliases will be removed.

Current version of Python 3.7 even produces a warning when you use the alias names:

./scripts/generateBoard.py:145: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working   elif isinstance(value, (collections.MutableMapping, collections.MutableSequence)) == True: 

In python 2.7 there is no collections.abc.

How can Python script handle this difference in the most convenient way, when it is meant to be used with (almost) any Python version? I'm looking for a solution which would ideally solve this mess in one central place, without having to use try: ... except: ... all over the script everywhere I need this type?

like image 721
Freddie Chopin Avatar asked Dec 30 '18 14:12

Freddie Chopin


People also ask

What is ABC collections?

ABC Collectors is known as a debt collections services company. Established in 1964, they have been in business for approximately 55 years, and have plenty of years under their corporation heading.

What is the difference between a generic collection object and a sequence object in Python?

To conclude this Python Sequence and collection tutorial, we will say that a sequence has a deterministic ordering, but a collection does not. Examples of sequences include strings, lists, tuples, bytes sequences, bytes arrays, and range objects. Those of collections include sets and dictionaries.

What is a Mutablemapping?

1.0. interface MutableMap<K, V> : Map<K, V> A modifiable collection that holds pairs of objects (keys and values) and supports efficiently retrieving the value corresponding to each key. Map keys are unique; the map holds only one value for each key.


1 Answers

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 
like image 158
Freddie Chopin Avatar answered Sep 17 '22 04:09

Freddie Chopin