Type Hint Basics
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 does not enforce type hints. They are purely annotations. mypy and pyright perform static checking.
2. Commonly Used Types
3. Optional · Union (Nullable)
4. Callable · Complex Types
5. Classes + Types
6. Type Checking — mypy
One-line Summary
def f(x: T) -> R: + list[int] + str | None — these three cover 90% of use cases.
💡 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
🤖 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.