Skip to content

collections.abc.Set, etc., missing _from_iterable() classmethod #15298

@finite-state-machine

Description

@finite-state-machine

The base class for non-mutable abstract sets, collections.abc.Set (and a few others in Lib/_collections_abc.py) provide a classmethod(_from_iterable(Iterable[...]) -> Set[...]) (or similar) class method, which serves as a single place to override how the results of set-wise operations are constructed.

C.f.: https://docs.python.org/3/library/collections.abc.html#examples-and-recipes

The class method in question, _from_iterable(), doesn't appear anywhere in typeshed (GitHub search of this repo, 2026-01-17).


Motivating example: I have a set-like class Region which acts as a set of all co-ordinates in a 2D area bounded min/max x and y co-ordinates. The results of set-wise operations involving a Region often aren't rectangular, and so can't be represented by a Region. Without _from_iterable(), collections.abc.Set tries to construct the result as Region(<Iterable[Coord]>), which won't (and can't) work. By overriding Set._from_iterable() in Region, I can construct results as set or frozenset instances, which can represent the results in all cases.

Metadata

Metadata

Assignees

No one assigned

    Labels

    stubs: incompleteAnnotations or sub-modules missing from an existing package or module

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions