roam/20201007142751-python_typin...

6.4 KiB
Raw Permalink Blame History

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

Limitations

  • Type hints do not guarantee purity.
  • Type hints are not checked at run-time.

Fun facts

  • Per PEP-285, Python's boolean inherits from int, hence True + True = 2.

Relevant PEPs

PEP Name Python Version
3107 Function Annotations 3.0
443 Single-dispatch generic functions 3.4
482 Literature Overview for Type Hints N/A
483 The Theory of Type Hints N/A
484 Type Hints 3.5
526 Syntax for Variable Annotations 3.6
544 Protocols: Structural subtyping (static duck typing) 3.8
557 Data Classes 3.7
560 Core support for typing module and generic types 3.7
561 Distributing and Packaging Type Information 3.7
563 Postponed Evaluation of Annotations 3.7
585 Type Hinting Generics In Standard Collections 3.9
586 Literal Types 3.8
589 TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys 3.8
591 Adding a final qualifier to typing 3.8
593 Flexible function and variable annotations 3.9
604 Allow writing union types as X Y 3.10
612 Parameter Specification Variables 3.10
613 Explicit Type Aliases 3.10
634 Structural Pattern Matching: Specification 3.10
635 Structural Pattern Matching: Motivation and Rationale 3.10
636 Structural Pattern Matching: Tutorial 3.10
638 Syntactic Macros
640 Unused variable syntax 3.10
646 Variadic Generics 3.11
647 User-Defined Type Guards 3.10
649 Deferred Evaluation Of Annotations Using Descriptors 3.13
654 Exception Groups and except* 3.11
655 Marking individual TypedDict items as required or potentially-missing 3.11
673 Self Type 3.11
675 Arbitrary Literal String Type 3.11
692 Using TypedDict for more precise **kwargs typing 3.12
695 Type Parameter Syntax 3.12
698 Override Decorator for Static Typing 3.12