Check that type of target is known [has-type]
Mypy sometimes generates an error when it hasn’t inferred any type fora variable being referenced. This can happen for references tovariables that are initialized later in the source file, and forreferences across modules that form an import cycle. When thishappens, the reference gets an implicit Any
type.
In this example the definitions of x
and y
are circular:
- class Problem:
- def set_x(self) -> None:
- # Error: Cannot determine type of 'y' [has-type]
- self.x = self.y
- def set_y(self) -> None:
- self.y = self.x
To work around this error, you can add an explicit type annotation tothe target variable or attribute. Sometimes you can also reorganizethe code so that the definition of the variable is placed earlier thanthe reference to the variable in a source file. Untangling cyclicimports may also help.
We add an explicit annotation to the y
attribute to work aroundthe issue:
- class Problem:
- def set_x(self) -> None:
- self.x = self.y # OK
- def set_y(self) -> None:
- self.y: int = self.x # Added annotation here