Context in type inference

Type inference is bidirectional and takes context into account. Forexample, the following is valid:

  1. def f(l: List[object]) -> None:
  2. 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:

  1. def foo(arg: List[int]) -> None:
  2. print('Items:', ''.join(str(a) for a in arg))
  3.  
  4. 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:

  1. def foo(arg: List[int]) -> None:
  2. print('Items:', ', '.join(arg))
  3.  
  4. a = [] # Error: Need type annotation for 'a'
  5. foo(a)

Working around the issue is easy by adding a type annotation:

  1. ...
  2. a: List[int] = [] # OK
  3. foo(a)