-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Description
Consider the following program:
computed_later = None # type: str
computed_later = 'hello'
print(computed_later)
When typechecked with:
$ mypy --strict-optional test_computed_later.py
The following error is emitted:
test_computed_later.py:1: error: Incompatible types in assignment (expression has type None, variable has type "str")
In this program, the assignment computed_later = None is intended to be a declaration, as described in PEP 484 (Type Hints):
In stubs it may be useful to declare the existence of a variable without giving it an initial value. This can be done using a literal ellipsis:
from typing import IO stream = ... # type: IO[str]In non-stub code, there is a similar special case:
from typing import IO stream = None # type: IO[str]Type checkers should not complain about this (despite the value None not matching the given type), nor should they change the inferred type to Optional[...](despite the rule that does this for annotated arguments with a default value of None). The assumption here is that other code will ensure that the variable is given a value of the proper type, and all uses can assume that the variable has the given type.
It appears that --strict-optional is not treating the None-assignment as a declaration in this case, which is inconsistent with PEP 484. Thoughts?