Python Type Hints Explained for Beginners
SkillVeris Team
Engineering Team

Type hints are optional annotations that declare what types your variables, arguments, and return values are expected to be.
In this guide, you'll learn:
- Python does not enforce type hints at runtime; tools like mypy and Pyright check them separately before you run the code.
- Hints make code self-documenting and let editors offer far better autocomplete and error detection.
- The typing module and modern built-in syntax cover lists, dicts, optionals, unions, and custom generic types.
- Optional[X] means a value can be X or None, one of the most common and useful hints.
1What Are Type Hints?
Type hints are annotations that tell readers and tools what type a variable, function argument, or return value is expected to be. Writing def greet(name: str) -> str declares that greet takes a string and returns a string. They were introduced in Python 3.5 and have become standard practice in professional codebases.
Crucially, Python itself ignores these hints at runtime; passing the wrong type will not raise an error just because of an annotation. Their power comes from static analysis tools and editors that read the hints to catch bugs before your program ever runs.
2Basic Syntax
The syntax is straightforward: put a colon and the type after a variable or parameter name, and use an arrow before the return type. You can annotate simple variables too, though function signatures are where hints earn their keep.
- name: str = 'Ada' # annotated variable
- age: int = 30
- price: float = 9.99
- is_active: bool = True
- def add(a: int, b: int) -> int: # annotated function
- return a + b
💡Pro Tip
You do not have to annotate everything. Start with function parameters and return types, which document the most important contracts in your code.
3Hinting Collections
Containers need to say what they contain. Modern Python (3.9+) lets you use the built-in types directly, so list[int] means a list of integers and dict[str, float] means a dictionary mapping strings to floats. Older code imported List and Dict from the typing module for the same purpose.
- scores: list[int] = [90, 85, 100]
- prices: dict[str, float] = {'apple': 0.5}
- coords: tuple[float, float] = (1.0, 2.0)
- names: set[str] = {'ada', 'linus'}
- from typing import List # older equivalent of list[...]
4Optional, Union, and None
Real functions often accept more than one type or allow a missing value. Optional[X] means the value is either X or None, and Union[X, Y] means it can be either type. Since Python 3.10 you can write X | Y instead, which reads more naturally.
Handling Missing Values
Optional is the honest way to say a value might be absent. It forces callers and checkers to consider the None case rather than assuming a value always exists.
from typing import Optional
def find_user(id: int) -> Optional[str]: # returns str or None
...
def parse(x: str) -> int | None: # 3.10+ shorthand
...
value: int | str = 5 # a union of two types5Checking Types With mypy
Because Python does not enforce hints, you run a separate type checker to benefit from them. mypy is the most established; Pyright (which powers Pylance in VS Code) is another popular choice. Install mypy, point it at your code, and it reports every place where the actual types disagree with the declared ones.
- pip install mypy
- mypy myscript.py # check a single file
- mypy . # check the whole project
- # mypy flags: passing a str where an int was declared, etc.
🔑Key Takeaway
Type hints only catch bugs if you actually run a checker. Add mypy or Pyright to your workflow, ideally in your editor and your CI pipeline.
6Why Use Type Hints at All?
Type hints pay off well beyond catching type errors. They serve as always-accurate documentation, unlock precise autocomplete in editors, and make refactoring safer because tools can trace how types flow through your code. On a team, they communicate intent that comments often fail to keep current.
- Self-documenting signatures: readers see expected inputs and outputs instantly.
- Better tooling: editors offer accurate autocomplete and inline warnings.
- Safer refactors: checkers flag call sites you would otherwise miss.
- Fewer runtime surprises: many bugs surface before the code runs.
7Common Mistakes to Avoid
Beginners tend to trip over the same few misunderstandings about how hints behave.
- Expecting hints to enforce types at runtime; they never do without extra libraries.
- Annotating a mutable default like def f(items: list = []) which shares state across calls; use None and create the list inside.
- Over-annotating trivial local variables and cluttering the code.
- Using Any everywhere, which silences the checker and defeats the purpose.
- Forgetting to actually run mypy or Pyright, so the hints go unchecked.
8Key Takeaways
Type hints are a low-cost, high-value addition to any growing Python codebase.
- Hints declare expected types but are not enforced at runtime.
- Run mypy or Pyright to actually catch mismatches.
- Use list[int], dict[str, float], and similar for collections.
- Optional[X] or X | None expresses values that may be missing.
- Start with function signatures and expand coverage gradually.
9Frequently Asked Questions
Q: Do Python type hints slow down my program? A: No. Hints are ignored by the interpreter at runtime and add essentially no overhead. They are used by external tools and editors, not by Python's execution engine.
Q: Does Python enforce type hints? A: Not on its own. Passing the wrong type will not raise an error from the hint alone. You need a static checker like mypy or Pyright to verify that your code matches its annotations.
Q: What is the difference between Optional and Union? A: Optional[X] is shorthand for Union[X, None], meaning a value is either X or None. Union[X, Y] allows any of the listed types. In Python 3.10+ you can write X | Y and X | None instead.
Q: Should I add type hints to an existing project? A: Yes, gradually. Start with the function signatures of your most-used modules, run a checker, and expand from there. You do not need to annotate everything at once to benefit.
Related Reading
Get The Print Version
Download a PDF of this article for offline reading.
About the Publisher
SkillVeris Team
Engineering Team
Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.
View all postsRelated Posts
Never miss an update
Get the latest tutorials and guides delivered to your inbox.
No spam. Unsubscribe anytime.