Home > OS >  mypy error: Incompatible return value type (got "object", expected "Dict[Any, Any]&qu
mypy error: Incompatible return value type (got "object", expected "Dict[Any, Any]&qu

Time:11-22

I have a python class that looks as following:

class TestClass():

    def __init__(self, input_data):
        self.input_data = input_data #always 'a' or 'b'

    def test(self) -> dict[int, Any]:
        a = {'a': {1:0, 2:0}, 'b': {2:0, 3:'string'}}
        return a[self.input_data]

running mypy results in the error message Incompatible return value type (got "object", expected "Dict[Any, Any]"). Is there a way to solve this problem?

I also get the same problem with one line if statements, e.g. if I return a different integer depending on a condition and annotate the return type as int, an error message is raised that "object" type is returned.

CodePudding user response:

You need to add a type annotation to a:

a: dict[str, Any] = {'a': {1:0, 2:0}, 'b': {2:0, 3:'string'}}

It seems like this function is returning a dict[int, Any], not a dict[str, Any], but I'm not sure what you intend.

  • Related