Context in type inference
Type inference is bidirectional and takes context into account. Forexample, the following is valid:
- def f(l: List[object]) -> None:
- l = [1, 2] # Infer type List[object] for [1, 2], not List[int]
In an assignment, the type context is determined by the assignmenttarget. In this case this is l
, which has the typeList[object]
. The value expression [1, 2]
is type checked inthis context and given the type List[object]
. In the previousexample we introduced a new variable l
, and here the type contextwas empty.
Declared argument types are also used for type context. In this programmypy knows that the empty list []
should have type List[int]
basedon the declared type of arg
in foo
:
- def foo(arg: List[int]) -> None:
- print('Items:', ''.join(str(a) for a in arg))
- foo([]) # OK
However, context only works within a single statement. Here mypy requiresan annotation for the empty list, since the context would only be availablein the following statement:
- def foo(arg: List[int]) -> None:
- print('Items:', ', '.join(arg))
- a = [] # Error: Need type annotation for 'a'
- foo(a)
Working around the issue is easy by adding a type annotation:
- ...
- a: List[int] = [] # OK
- foo(a)