Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

mypy

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 ?

like image 726
user5049567 Avatar asked Dec 07 '25 18:12

user5049567


1 Answers

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]()
like image 156
Andrew McDowell Avatar answered Dec 09 '25 15:12

Andrew McDowell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!