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

Type Hints

🏷️ Type Hints

Type hints tell us what type of data a variable or function is expected to contain or return.

They make code easier to understand and help tools like IDEs and type checkers detect possible mistakes.


1️⃣ Variable Type Hints

You can specify the expected type of a variable using :.

name: str = "Tisha"
age: int = 23
height: float = 5.5
is_student: bool = True

Here:

name       β†’ str
age        β†’ int
height     β†’ float
is_student β†’ bool

πŸ“‹ Collections

You can also specify the types of values inside collections:

names: list[str] = ["Tisha", "Rahul"]
marks: dict[str, int] = {
    "Math": 90,
    "English": 85
}
numbers: tuple[int, ...] = (1, 2, 3)

This tells us:

list[str]        β†’ List containing strings
dict[str, int]   β†’ Dictionary with string keys and integer values
tuple[int, ...]  β†’ Tuple containing integers

2️⃣ Function Type Hints

Type hints can be added to parameters and the return value of a function.

def add(a: int, b: int) -> int:
    return a + b

Here:

a: int    β†’ a is expected to be an integer
b: int    β†’ b is expected to be an integer
-> int    β†’ function is expected to return an integer

πŸ”Ή Another Example

def greet(name: str) -> str:
    return "Hello " + name
name: str β†’ Parameter should be a string
-> str    β†’ Function returns a string

πŸ”Ή Function Returning Nothing

If a function doesn't return a value:

def greet(name: str) -> None:
    print("Hello", name)

-> None indicates that the function does not return a meaningful value.


⚠️ Important

Type hints do not automatically enforce types.

def add(a: int, b: int) -> int:
    return a + b

print(add("Hello", "World"))

Python can still execute this and produce:

HelloWorld

Type hints are mainly guidance for developers, IDEs, and static type-checking tools.