Python Collection Types for Typehinting
Python Collection Types for Typehinting
I've split the collection structure into these segments
- linear types : list-like collections. Use
SequenceorMutableSequence - mapping types : key-value collections. Use
MappingorMutableMapping - nonlinear types : unordered collections. Use
SetorMutableSet. For generators, it'sGenerator[YieldT][1]. - async types : async-coloured collections
- other types : other things
Linear Types
The linear types are list-like. If you want to manipulate the collection, you will probably want Sequence (which includes tuple and list) or MutableSequence. If all you need is to traverse it, use Iterable
Instead of using TupleOf = tuple[T, ...], use Sequence[T].
Mapping Types
Mapping types are key-value pairs, or something like that. Use Mapping or MutableMapping, which includes dict and
several relatives.
Nonlinear Types
These collections have unordered membership, but are not associated with values. This does not extend to other semantics of set. For example, a KeysView can have duplicates, although set does not. You are probably not interested in MappingView.
Async Types
Other Types
If you think about it, a mapping is a function that turns keys into values. So a Callable is sortof a mapping type.
The full signature is
Generator[YieldType, SendType, ReturnType], butSendTypeandReturnTypedefault toNoneso you can just useGenerator[YieldType]. You can also just useIterator[YieldType]. You could also useIterable[YieldType], but you might be confused that you can't start multipleIteratorsof it (double-traversal will confuse everything). ↩︎