Search code examples
pythontype-hintingmypy

mypy error: Incompatible return value type (got "object", expected "Dict[Any, Any]")


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.


Solution

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

    Edit: from your edit it seems that you do want dict[int, Any]. In that case, you can narrow a’s type to dict[str, dict[int, Any]].