3.8 KiB
3.8 KiB
Python Typing
Python does not require nor enforce strict typing, and instead takes a dynamic approach using Duck Typing.
Gradual Typing support for Python is provided via type hints as described in PEP-484 (which covers Nominal Typing) and expanded upon in PEP-544 (which covers Structural Typing).
Variables, function arguments, and return values can have their types annotated, e.g. "variable x has type integer" or "function y takes a string and returns a list of dictionaries". While these are optional and not checked at run-time, they serve as documentation and can be used by various type checkers to ensure program correctness.
Available Type Checkers
- Mypy
- http://mypy-lang.org/
- Pyright (Microsoft)
- https://github.com/Microsoft/pyright
- Pyre (Facebook)
- https://pyre-check.org/
- Pytype (Google)
- https://google.github.io/pytype/
Limitations
- Type hints do not guarantee purity.
- Type hints are not checked at run-time.
Fun facts
- Per PEP-285, Python's
boolean
inherits fromint
, henceTrue + True = 2
.
Relevant PEPs
- PEP 3107 – Function Annotations
- PEP 443 – Single-dispatch generic functions
- PEP 482 – Literature Overview for Type Hints
- PEP 483 – The Theory of Type Hints
- PEP 484 – Type Hints
- PEP 526 – Syntax for Variable Annotations
- PEP 544 – Protocols: Structural subtyping (static duck typing)
- PEP 557 – Data Classes
- PEP 560 – Core support for typing module and generic types
- PEP 561 – Distributing and Packaging Type Information
- PEP 563 – Postponed Evaluation of Annotations
- PEP 585 – Type Hinting Generics In Standard Collections
- PEP 586 – Literal Types
- PEP 589 – TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys
- PEP 591 – Adding a final qualifier to typing
- PEP 593 – Flexible function and variable annotations
- PEP 604 – Allow writing union types as X | Y
- PEP 612 – Parameter Specification Variables
- PEP 613 – Explicit Type Aliases
- PEP 634 – Structural Pattern Matching: Specification
- PEP 635 – Structural Pattern Matching: Motivation and Rationale
- PEP 636 – Structural Pattern Matching: Tutorial
- PEP 638 – Syntactic Macros
- PEP 640 – Unused variable syntax
- PEP 646 – Variadic Generics
- PEP 647 – User-Defined Type Guards