Reputation: 216
I check my code using mypy
. I got these errors:
I have an object names: List[str]
, for len(names)
I get
Argument 1 to "len" has incompatible type "Optional[List[str]]"; expected "Sized"
When I try to index like names[i]
I get:
Value of type "Optional[List[str]]" is not indexable
I have an object matrix: List[List[int]]
, similarly matrix[i][j]
Value of type "Optional[List[List[int]]]" is not indexable
I have an object
def func() -> Dict[str, List[str]]
g = {"1": ["2"],
"2": ["3"]}
return g
annotated as Dict[str, List[str]]
, I get an error:
Incompatible return value type (got "Dict[str, object]", expected "Dict[str, List[str]]")
I don't understand, why I got this type. If I change it to Dict[str, object]
, I get another errors in my code like in 4.
When I try to use my object:
d: DefaultDict[str, List[str]] = defaultdict(list)
for obj in g:
d[obj].extend(g.get(obj))
I get this error:
Argument 1 to "extend" of "list" has incompatible type "Optional[List[str]]"; expected "Iterable[str]"
I am new in python
and don't understand principles of working with mypy
- how should I annotate types so as not to get similar errors?
Upvotes: 2
Views: 4801
Reputation: 69
In number 4.
when you use .get()
method the return type becomes optional i.e. if you were expecting to get List[str]
it would be Optional[list[str]]
this is equivalent to
[None, List[str]]
. To overcome this you could do following:-
if g.get(obj) is None:
raise RunTimeError("Not found")
Upvotes: 2