How to correct type errors with mypy library

Submitted 3 years, 7 months ago
Ticket #138
Views 1579
Language/Framework Python
Priority Medium
Status Closed

I check my code using mypy. I got these errors:

  1. 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

  2. I have an object matrix: List[List[int]], similarly matrix[i][j]

    Value of type "Optional[List[List[int]]]" is not indexable

  3. I have an object

     g = {"1": ["2"],
      "2": ["3"]}

    annotated as Dict[str, List[str]], I get an error:

    Incompatible return value type (got "Dict[str, object]", expected "Dict[str, List[str]]")

  4. I don't understand, why I got this type. If I change it to Dict[str, object], I get another errors in my code.

  5. When I try to use my object:

     for obj in g:
         g.get(obj)

    I get this error:

    Argument 1 to "extend" of "list" has incompatible type "Optional[List[str]]"; expected "Iterable[str]"

  6. 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?

Submitted on Sep 10, 20
add a comment

1 Answer

Verified

from types import StringType, UnicodeType
from typing import Union

MyStringTypes = Union[StringType, UnicodeType]

def f(value):     
    # type: (MyStringTypes) -> MyStringTypes
    return value

Submitted 3 years, 6 months ago


Latest Blogs