user5049567
user5049567

Reputation: 99

Mypy: Incompatible type (object) with a dictionary of functions

The following code:

from typing import Union

def a() -> int:
    return 1

def b() -> str:
    return 'a'

def c(arg: str = 'a') -> Union[int, str]:
    return {'a': a, 'b': b}[arg]()

triggers the following mypy exception:

error: Incompatible return value type (got "object", expected "Union[int, str]")

A workaround would be to use:

return a() if arg == 'a' else b()

in which case Mypy doesn't complain, but the dictionnary syntax is still helpful if there are more than 2 functions. Is there a way around it, or is it a Mypy bug ?

Upvotes: 3

Views: 3231

Answers (1)

Andrew McDowell
Andrew McDowell

Reputation: 2980

I think the issue is that you aren't declaring the allowed types of the dictionary. Although it's clear in your code that there are only two types of output in the dictionary, there's nothing from a typing point of view to stop another function d() being added to it.

You could try the following to get around this issue:

from typing import Union, Dict, Callable

output_dictionary : Dict[str, Union[Callable[[], int],Callable[[], str]]] = {'a': a, 'b': b}

def c(arg: str = 'a') -> Union[int, str]:
    return output_dictionary[arg]()

Upvotes: 3

Related Questions