Introduction to Python Type Annotations
Brief History
- 1990: Guido van Rossum created Python (dynamically typed language)
- 2000: Initial mention of type hinting
- 2014: PEP 484 introduced type annotations
- Today: Type annotations in Python 3.6+
- Python remains dynamically typed
Update on Current State
- Type annotations don’t change Python’s behavior
- Serve as a form of structured documentation
Examples and Syntax
- Basic Type Annotations:
V1: int = hello
gives an error with type checker (variable type mismatch)
- Class Annotations:
class Foo: var1: int Foo.var1
doesn’t influence runtime, stored in __annotations__
- Function Annotations:
def bar(values: List[int]) -> int:
return sum(values)
- Inheritance with Annotations:
class Animal:
pass
class Dog(Animal):
pass
Type Syntax Notes
- Union:
var: Union[int, float, str]
or var: int | float | str
- Custom Types:
MyNumber = Union[int, float]
def func(value: MyNumber) -> MyNumber:
return value
- Generics: Lists and Dictionaries
from typing import List, Dict
List[int]
Dict[str, int]
Tuple[int, str]
Tuple[int, ...] # Infinite length
Tuple[Union[int, str], ...]
Protocols and TypeVars
- Protocols: Interfaces specifying methods without implementation
from typing import Protocol
class EmailSender(Protocol):
def send_email(self, to: str, subject: str, body: str) -> None:
...
- TypeVars: For generic types with constraints
from typing import TypeVar
T = TypeVar('T', str, int)
Tools and Best Practices
- Type Checkers:
mypy
(most mature), pytype
, Pylance
, pyright
- Install and Run mypy:
pip install mypy
mypy <your_code>
- Configuration:
- Use
mypy.ini
, mypy.conf
, or setup.cfg
for project settings
- Stub Files: For third-party packages without annotations (use
.pyi
files)
Benefits of Type Annotations
- Improves code documentation and readability
- Enhances IDE features and auto-completion
- Helps catch bugs early and ensures code reliability
Conclusion
- Recommendation: Start using a type checker in your codebase
- Contact: [Contact details provided]
Example Additional Terms
- Type Hinting: Often used interchangeably with type annotations
- Type Comments: For backwards compatibility with older Python versions