C
Python/Types/Lesson 20

Type Hint Basics

1 hr·theory
Python

Type Hint Basics

🎯 After reading this lesson

Once you finish this lesson, you will be able to confidently do the following 3 things.

  • ✅ Use typing.Optional · Union · Literal · TypedDict
  • ✅ Patterns to pass mypy --strict
  • ✅ Reusable types with Generic + TypeVar

Keep the learning goals as a checklist, and close the lesson once you can answer all of them.

Type Hints — Code + Execution Results

x: int = type annotation on variables and functions. Python 3.5+ (PEP 484). No runtime impact; used by IDEs and mypy.


1. Types on Functions

python
# ❌ No types — what does it accept and return?
def add(a, b):
    return a + b

# ✅ With type annotations
def add(a: int, b: int) -> int:
    return a + b

print(add(3, 5))    # 8
# add("a", "b")     # mypy catches this, but *works fine at runtime*

⚠️ Python does not enforce type hints. They are purely annotations. mypy and pyright perform static checking.


2. Commonly Used Types

python
age: int = 28
height: float = 175.5
name: str = "Hong Gildong"
is_student: bool = True
scores: list[int] = [85, 92, 78]            # 3.9+
person: dict[str, int] = {"name": 1}        # 3.9+
coords: tuple[float, float] = (37.5, 127.0)
tag_set: set[str] = {"a", "b"}

3. Optional · Union (Nullable)

python
def find(name: str) -> str | None:           # 3.10+ — using |
    return data.get(name)

# For 3.9 and below:
from typing import Optional
def find(name: str) -> Optional[str]:
    return data.get(name)

# Union — multiple types allowed
def process(x: int | str) -> str:            # 3.10+
    return str(x)

4. Callable · Complex Types

python
from typing import Callable

# A function that accepts another function
def apply(f: Callable[[int], int], x: int) -> int:
    return f(x)

result = apply(lambda n: n * 2, 5)           # 10

5. Classes + Types

python
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int
    friends: list["Person"] = None           # forward reference

def greet(p: Person) -> str:
    return f"Hello {p.name}"

6. Type Checking — mypy

bash
$ pip install mypy
$ mypy my_file.py
# error: Argument 1 to "add" has incompatible type "str"; expected "int"

One-line Summary

def f(x: T) -> R: + list[int] + str | None — these three cover 90% of use cases.

💻 Type Hint Fundamentals
# Variable type hints
name: str = "Chul-soo"
age: int = 25
height: float = 175.5
is_student: bool = True

# Function type hints
def greet(name: str) -> str:
    return f"Hello, {name}!"

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

# No return value
def print_hello() -> None:
    print("Hello")

# List, Dictionary (Python 3.9+)
def process_items(items: list[str]) -> dict[str, int]:
    return {item: len(item) for item in items}

# Python 3.8 and below
from typing import List, Dict
def process_items_old(items: List[str]) -> Dict[str, int]:
    return {item: len(item) for item in items}

# Class method
class Person:
    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age
    
    def greet(self) -> str:
        return f"Hello, {self.name}"

💡 Key Points

1. Type hints are just hints — they are not enforced
2. Python 3.9+: list[str], dict[str, int]
3. Python 3.8 and below: from typing import List, Dict

Python features concise, readable syntax and is used across a wide range of domains. As an interpreted language, it can be run immediately in a REPL environment. It follows the PEP 8 coding style guide and supports automatic formatting with Black/autopep8. Type hints improve code readability and IDE support. Package management is done via pip, and virtual environments are set up with venv/conda.

🐍 Try It Yourself — Type Hint Basics

Run the concepts above as actual code. The fastest way to learn is to change values and verify the behavior yourself.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try Asking AI Like This

Knowing the concepts from this lesson lets you give AI specific instructions. Instead of a vague "fix this," you can make vocabulary-driven requests — and that is where token savings begin.

  • "Add precise type annotations to this function signature using typing.Optional · Literal · TypedDict"
  • "Strengthen the types in this code so it passes mypy --strict"

Why This Reduces Tokens

Without knowing the concepts, you have to ask "what does that mean?" after receiving an AI response. That follow-up question is what burns tokens. Learn the concept once, and the conversation ends in a single exchange.

Type Hinting - Python