π·οΈ Type Aliases
A type alias is a custom name given to an existing type or combination of types.
It makes complex type hints shorter and easier to understand.
πΉ Basic Type Alias
UserID = int
user_id: UserID = 101Here:
UserID β another name for intπΉ Alias for Complex Types
Instead of repeatedly writing:
dict[str, int]we can create an alias:
StudentMarks = dict[str, int]
marks: StudentMarks = {
"Math": 90,
"English": 85
}π Type Alias with Multiple Types
ID = int | str
user_id: ID = 101
user_id = "A101"ID can be either int or str.
π Explicit Type Alias
For clearer type-checking, Python provides TypeAlias:
from typing import TypeAlias
StudentMarks: TypeAlias = dict[str, int]Type alias = A meaningful name for an existing type.