Python Mastery – From Basics to Brilliance / Type Hints and Code Quality

Type Aliases in Python

🏷️ 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 = 101

Here:

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.