backports-abc
A backport of recent additions to the 'collections.abc' module, providing Abstract Base Classes (ABCs) like `Generator`, `Awaitable`, and `Coroutine` for older Python versions (including Python 2.x, 3.2, 3.3, 3.4). It allows for direct imports of these ABCs or offers a `patch()` function to integrate them into the `collections` or `collections.abc` module namespace. The latest release, 0.5, was released in 2016.
Warnings
- gotcha The `patch()` function modifies Python's standard `collections` or `collections.abc` module in-place. In Python 2.x and 3.2, it patches `collections`, while for Python 3.3+ it targets `collections.abc`. This global state modification can potentially lead to unexpected behavior or conflicts in complex environments. It will not overwrite names already present.
- deprecated This library has not been updated since 2016. While functional for its intended purpose of supporting older Python versions, its inactive maintenance status means it will not receive new features or bug fixes. Users should consider upgrading to a Python version where these ABCs are natively available in the standard library if possible.
- gotcha The primary use case for `backports-abc` is to provide `collections.abc` elements (like `Generator`, `Awaitable`, `Coroutine`) that were introduced in later Python versions. Using this library on Python versions where these ABCs are already available (e.g., Python 3.5+ for `Coroutine`) is unnecessary and could potentially mask issues if an older, possibly incomplete, backported definition were to take precedence, though the library attempts to avoid overwriting existing names.
Install
-
pip install backports-abc
Imports
- Coroutine
from collections.abc import Coroutine
from backports_abc import Coroutine
- Generator
from collections.abc import Generator
from backports_abc import Generator
- Awaitable
from collections.abc import Awaitable
from backports_abc import Awaitable
- patch
import backports_abc; backports_abc.patch()
Quickstart
import sys
if sys.version_info < (3, 5): # Coroutine/Awaitable were added in 3.5
try:
from backports_abc import Coroutine, Generator
except ImportError:
# Fallback for even older Python or if backport isn't installed
# (though this should not happen if backports_abc is installed)
from collections import Generator # Python 2.x / 3.2 might have it here
# Coroutine might not be available at all
else:
# In Python 3.3+, ABCs are in collections.abc
# Coroutine/Awaitable from 3.5
from collections.abc import Coroutine, Generator
print(f"Using Coroutine from: {Coroutine.__module__}")
print(f"Using Generator from: {Generator.__module__}")
# Example of using patch (generally less recommended due to global state)
# if sys.version_info < (3, 5):
# import backports_abc
# backports_abc.patch()
# from collections.abc import Coroutine as PatchedCoroutine
# print(f"Patched Coroutine from: {PatchedCoroutine.__module__}")