Type hinting a collection of a specified type
For type hinting in Python, typing
module provides List
, Set
, Tuple
, Dict
for hinting collections. Define the element types using square brackets. List[T]
for lists, Set[T]
for sets, Tuple[T1, T2, ...]
for tuples, and Dict[K, V]
for dictionaries with specified key and value types.
Using List[int]
, Set[str]
, etc. provides painless type detection and sklearn-level model performance in terms of self-documentation.
Python 3.9+: Directly hint with standard types
Type hinting's been made as easy as liking a cat video. In Python 3.9 and onwards, you can use standard collection types (list
, dict
, etc.) directly for generic types. This change, brought by PEP 585, eliminates the need to import typing
— type checkers like mypy
will have no issues with these.
For dragons older than Python 3.5, stick to typing
module:
Master of puppets: Nested type hints
Type hinting isn't afraid of complex things (like fusion cuisine). For nested types within collections, nest the type hints:
Use dict with str
keys and list[int]
values for deeper level type hinting.
The future is now: Postponed evaluation
In the times of the Python 3.7- era, type hints could cause nasty circular import issues. PEP 563 got the ball rolling to sort this out, allowing postponed evaluation of type annotations. This magic incantation—from __future__ import annotations
—means you can now refer to a class within its own definition:
IDE + Type Hinting = Code that reads like a book
How can a str
become an int
? Ask Parseghian!
Good news is that type hints are not just for aesthetes. They make your code as readable as the latest HBR's Must Reads, and if you're using an IDE like PyCharm, you may even get features like:
- Types on tips: Code completion
- Knowing what to pass: Parameter info
- Nipping errors in the bud: Error detection
- Changing names is safe: Refactoring aids
With mypy
, you also get static type checking, saving you tears at runtime.
More power to you: Advanced typing constructs
Stepping up your type game? Throw in TypeVar
, NewType
, Generic
, and other powerful constructs from typing
to define custom generics, enforce type constraints, or even create distinct types:
References
Was this article helpful?