What are the differences between Set, FrozenSet, MutableSet and AbstractSet in python typing module?

Viewed 8433

I am trying to annotate my code with types but I am a little confused when it comes to sets. I read some points in PEP 484:

Note: Dict , List , Set and FrozenSet are mainly useful for annotating return values. For arguments, prefer the abstract collection types defined below, e.g. Mapping , Sequence or AbstractSet .

and

Set, renamed to AbstractSet . This name change was required because Set in the typing module means set() with generics.

but this does not help.

My first question is: what are the commonalities and differences between Set, FrozenSet, MutableSet and AbstractSet?

My second question is: why if I try

from collections import FrozenSet

I get

ImportError: cannot import name 'FrozenSet'

?

I am using Python 3.4 and I have installed mypy-lang via pip.

4 Answers

Two years late to the party, but anyway...

You can think of AbstractSet and MutableSet as like an interface in Java or an abstract base class in Python. Python's builtin set() and frozenset() are one implementation, but someone could create another implementation that doesn't use the builtins at all.

FrozenSet and Set, on the other hand, represent the types of the concrete built in classes frozenset and set.

For example, the "interface" types don't have union methods, while the concrete types do. So:

def merge(a: Set[str], b: Iterable[str]) -> Set[str]:
    return a.union(b)

will type check just fine, but if you change the type of a to AbstractSet, mypy says:

typetest.py:7: error: "AbstractSet[str]" has no attribute "union"

These type names are indeed a little confusing. There was a related discussion on mypy Gitter, and Guido provided a clarification.

typing.AbstractSet and typing.MutableSet are the types for ABCs (abstract base classes), not concrete implementations of the set type:

  • typing.AbstractSet is the type for collections.abc.Set, which is an ABC (abstract base class) for an immutable set.
  • typing.MutableSet is the type for collections.abc.MutableSet, which is an ABC for a mutable set.

typing.Set and typing.FrozenSet are the types for concrete set implementations, available in the stdlib:

  • typing.Set is the type for stdlib set, which is a concrete implementation of a mutable set.
  • typing.FrozenSet is the type for stdlib frozenset, which is a concrete implementation of an immutable set.
Related