PEP 526 – Syntax for Variable Annotations

PEP 526 – Syntax for Variable Annotations

PEP 526, a significant milestone in Python's evolution, introduced a new syntax for variable annotations. This introduction will delve into the intricacies of this syntax, its implications, and its impact on Python's readability and efficiency.

This PEP aims at adding syntax to Python for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments.

Since type comments aren’t actually part of the language, if a Python script wants to parse them, it requires a custom parser instead of just using ast.

Do not evaluate annotations, treat them as strings

Implement annotations as a descriptor

The majority of these issues can be alleviated by making the syntax a core part of the language.

Having a dedicated annotation syntax for class and instance variables will pave the way to static duck-typing as a complement to nominal typing defined by PEP 484

Annotations for local variables will not be evaluated

Annotating a local variable will cause the interpreter to treat it as a local, even if it was never assigned to.

Types of locals and globals can be annotated

Being able to omit the initial value allows for easier typing of variables assigned in conditional branches

Local annotations at function definition time

Store variable annotations also in function scope

Variable Annotations

Only single assignment targets and single right hand side values are allowed. Annotations for module level variables, class and instance variables, and local variables should have a single space after corresponding colon. There should be no space before the colon.

No:

A new covariant type ClassVar[T_co] is added to the typing module. It accepts only a single argument that should be a valid type, and is used to annotate class variables that should not be set on class instances.

Source

Get in