Variable Annotations: Enhancing Python's Type System
Variable annotations were introduced in Python 3.6, following the implementation of type hints with PEP 484. While type hints merely hinted at the expected type of a variable, annotations take the concept further by allowing you to directly specify a variable's type.
Syntax and Features
The new annotation syntax allows for both standalone annotations and annotations during assignments:
# Standalone annotation number: int # Annotation during assignment primes: List[int] = []
The annotated_assignment_stmt syntax covers this new syntax, introducing the ":" character as a delimiter.
In addition, Python 3.6 introduces the annotations attribute for modules and classes. This attribute contains the type annotations for the defined variables.
Accessing Annotations
To access annotations, you can use the get_type_hints function from the typing module. For example:
>>> from typing import get_type_hints >>> primes: List[int] = [] >>> captain: str >>> get_type_hints(__main__) {'primes': typing.List[int]}
Example
Consider the example provided in the question:
primes: List[int] = []
This annotation indicates that the primes variable is a list of integers. Any assignment to this variable must adhere to this type.
Class Variables and StarShip
The Stats variable in the StarShip class is an instance variable, not a class variable. ClassVar is a special type that denotes class variables. Currently, Starship.stats is an instance variable with the type Dict[str, int].
Usage
Variable annotations are optional and primarily intended for use by type-checking tools. They provide an easy and structured way to specify type metadata, enhancing code readability and facilitating the development of custom type-related tools and libraries.
The above is the detailed content of How Do Variable Annotations Enhance Python's Type System?. For more information, please follow other related articles on the PHP Chinese website!