Variable type hints are not validated inside function

Viewed 116

When you execute this code:

from typing import Dict

bar: Dict[int, int, int] = dict()

an exception TypeError with a message Too many parameters for typing.Dict; actual 3, expected 2 is raised. But when you define the variable inside a function:

from typing import Dict

def foo():
    bar: Dict[int, int, int] = dict()

foo()

no exception is raised this time. Is this an expected behavior or a bug?

1 Answers

It is intended behavior and is defined at PEP 526 -- Syntax for Variable Annotations #Runtime Effects of Type Annotations.

Annotating a local variable will cause the interpreter to treat it as a local, even if it was never assigned to. Annotations for local variables will not be evaluated:

def f():
    x: NonexistentName  # No error.

However, if it is at a module or class level, then the type will be evaluated:

x: NonexistentName  # Error!
class X:
    var: NonexistentName  # Error!

In addition, PEP 563 -- Postponed Evaluation of Annotations defines that using from __future__ import annotations with python 3.7+ prevents these annotations from being evaluated.

This PEP proposes changing function annotations and variable annotations so that they are no longer evaluated at function definition time. Instead, they are preserved in __annotations__ in string form.

from __future__ import annotations
from typing import Dict

bar: Dict[int, int, int] = dict()  # no errors
Related