Explaining Variable Annotations as Extended Functional Type Hints in Python
2 min readOct 14, 2022
The aim of this page📝 is to resolve the “wtf” I experienced with looking into this code (does not look like Good Ol Python I’ve been used to)
tf: Terraform = tf_context.version[version]
— https://commadot.com/wtf-per-minute/
TYPE HINTS, CONTINUED
- Once upon a time, the PEP 484 introduced type hints, a.k.a. type annotations.
- While its main focus was function annotations, it also introduced the notion of type comments to annotate variables
- Then, PEP 526 came along and finalized that by adding type hints/annotations for variables
- Variable Type Hints (Type annotations) can be added with
: <type>
to an assignment statement or a single expression indicating the desired type of the annotation target to a third-party type checker or just a reader
my_var: int
my_var = 5 # Passes type check.
other_var: int = 'a' # Flagged as error by type checker,
# but OK at runtime.
- Although a variable annotation is parsed as part of an annotated assignment, the assignment statement is optional
- The PEP states that “ the target of the annotation can be any valid single assignment target, at least syntactically (it is up to the type checker what to do with this)”,
- Note that the type doesn’t need to exist to be annotated.
d = {}
d['a']: int = 0 # Annotates d['a'] with int.
d['b']: int # Annotates d['b'] with int.
- Normally, the annotation expression should evaluate to a Python type
- After all the main use of annotations is type hinting but it is not enforced.
- The annotation can be any valid Python expression, regardless of the type or value of the result
- As you can see, at this time type hints are very permissive and rarely mechanically useful, unless you have a static type checker such as mypy
- Or you want to signalize to a reader that the binding has a specific custom type which is exactly what was the motive behind the initial WTF of
tf: Terraform = tf_context.version[version]