2 minutes
Type Hinting and Variable Annotations: Static Types Come to Python
Welcome to part four of our Python 3 features series! Today, we’re taking a peek at type hints and variable annotations, tools that make your code easier to read and help catch bugs early.
Python’s always been dynamically typed, but sometimes you want a bit of static typing love. Type hints let you sprinkle type info without changing how the code runs.
Why Type Hints?
- Readability: Other developers (and future you) can see what types of values a function expects and returns.
- Tooling: Linters and IDEs use hints to catch mistakes before you even run the code.
- Documentation: Your function signatures become self-documented.
Function Annotations (PEP 484)
Add types to your function’s parameters and return value:
from typing import List, Optional
def greet(name: str) -> str:
return f"Hello, {name}!"
# A function taking a list of ints and maybe returning a str:
def process(data: List[int]) -> Optional[str]:
if not data:
return None
return ",".join(str(x) for x in data)
These hints don’t enforce types at runtime, but tools like mypy
can analyze your code:
$ mypy script.py
Variable Annotations (PEP 526)
You can also annotate variables:
from typing import Dict
# Simple annotation:
count: int = 0
# More complex:
config: Dict[str, str] = {
'host': 'localhost',
'port': '8080',
}
This makes your intent clear and helps static analyzers.
Tools that Use Type Hints
- mypy: Static type checker
- pyright: Fast type checking in VS Code
- pylint, flake8: Linters that can warn about type mismatches
- IDE support: autocompletion, inline docs, and error squiggles
That’s the quick tour of type hints and annotations. Next time, we’ll dive into f-strings and other neat syntax tricks to make your string formatting and numeric literals sparkle. Happy typing!