backports-abc

0.5 · maintenance · verified Wed Apr 15

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

Install

Imports

Quickstart

Demonstrates the recommended conditional import pattern to use `backports-abc` when `collections.abc` is missing or incomplete, falling back to the standard library where available. It primarily targets Python versions where `Coroutine` and `Awaitable` (Python < 3.5) or `collections.abc` itself (Python < 3.3) are not present or incomplete. The `patch()` function is also available but modifies global state.

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__}")

view raw JSON →