iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Type Hints

Type hints (PEP 484) annotate variables, parameters, and returns with their expected types. Python doesn't enforce them at runtime, but tools like mypy and pyright catch mismatches before the code runs.

The shape

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

name: str = 'Ada'
ages: list[int] = [36, 56, 42]
config: dict[str, str] = {'host': 'localhost'}

Optional / Union

PYTHON
from typing import Optional, Union

def greet(name: Optional[str] = None) -> str:
    return f'Hi, {name or "friend"}'

def square(x: Union[int, float]) -> float:
    return x * x

# 3.10+ shorthand
def square2(x: int | float) -> float:
    return x * x

Common shapes

AnnotationMeans
list[int]List of ints.
dict[str, int]String→int dict.
tuple[int, str, bool]Three-element tuple.
Callable[[int], str]Function taking int, returning str.
Iterable[T]Anything iterable yielding T.
AnyBail out — accept anything.
NoneReturns nothing.

Why bother

  • IDE autocomplete — your editor knows what methods are valid.
  • Static checkingmypy catches bugs before runtime.
  • Self-documenting — function signatures show intent.
  • Refactors are safer — rename a field, the type checker finds every caller.

Dataclasses lean on them

PYTHON
from dataclasses import dataclass

@dataclass
class User:
    id: int
    name: str
    active: bool = True
Tip: Don't over-annotate. Annotate function signatures and module-level config; let local variables stay inferred.

Example

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

from typing import Optional
def greet(name: Optional[str] = None) -> str:
    return f'Hi, {name or "friend"}'

print(add(2, 3))
print(greet())
Try it Yourself »

Exercise

Annotate the return type of a function.

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

Test yourself

Q1. Type hints are enforced…
Q2. Optional[X] is equivalent to…
Q3. Modern union syntax (3.10+) is…

Discussion

Loading…