Python (3.5+) Type Hints
Using Type Aliases
What Are Python Type Hints?
● New in 3.5 (provisional)
● PEP484
● Optional (not enforced at runtime)
○ Linter use recommended instead
● Function annotations
● Type Aliases, NewType, Callable, Generics ...
Type Alias
Type Alias Linting
Type Alias At Runtime
Type Alias
Type Alias At Runtime
Type Alias
Type Alias
Type Alias (Any type, implicit)
Type Alias (Any type, implicit)
Type Hints Advantages
● Clarifies, “enforces” intent
● Improves readability
○ Simplifies type signatures
● Improves testability
● May prevent bugs
Type Hints Disadvantages
● Lose dynamic typing flexibility
● Syntax complexity

Python type hints

Editor's Notes

  • #3 PEP=Python Enhancement Proposal PEP484 primary focus is function annotation See typing module for others… - NewType is for distinct types, Generics is for statically inferring types in containers
  • #5 PyCharm (community ed. used here) does linting mypy: new, experimental static type checker
  • #7 PyCharm community edition
  • #8 danger of truncation errors...
  • #9 PyCharm community edition
  • #10 PyCharm community edition
  • #11 if type not specified, assumes Any
  • #13 may prevent bugs from making assumptions about expected input and output types
  • #14 Adds complexity to Python syntax. Good IDE like PyCharm provides prompts