liveBook · Manning

Collections.abc

As explained in Python How-To

collections.abc is a Python standard-library module defining abstract base classes for common container and iterable interfaces.

Use collections.abc when code should accept objects by their supported interface rather than by a fixed list of concrete classes. Its abstract base classes provide generic runtime checks for container and iterable-like behavior. section 10.1.3

Accept any collection of urgencies

from collections.abc import Collection def filter_tasks(tasks, by_urgency): if isinstance(by_urgency, Collection): filtered = [x for x in tasks if x.urgency in by_urgency] else: filtered = [x for x in tasks if x.urgency == by_urgency] return filtered Collection requires __contains__, __iter__, and __len__, so the function can handle list, tuple, set, Series, and custom collection classes without naming each type. section 10.1.3

Listing 10.4 Checking an object’s type against an abstract class
from collections.abc import Collection

def filter_tasks(tasks, by_urgency):
   if isinstance(by_urgency, Collection):
       filtered = [x for x in tasks if x.urgency in by_urgency]
   else:
       filtered = [x for x in tasks if x.urgency == by_urgency]
   return filtered

Inspect the focused filter_tasks implementation using Collection with isinstance. section 10.1.3

How Python How-To covers it

How deep it goes
Defines Collection through three required special methods and demonstrates its use with isinstance, without surveying other abstract base classes.
Examples
Uses filter_tasks with list, tuple, set, pandas Series, and custom collection classes as accepted urgency inputs.
What it assumes
Assumes familiarity with classes, interfaces, and isinstance-based runtime type checks.
What you can do after
Apply Collection with isinstance to write flexible functions that operate across compatible container types.
How it connects
Connects abstract base classes, interfaces, isinstance, type checking, and concrete collection classes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.