Function that returns certain types depending of the value of a parameter #9834
-
Hello, I have a question about the overloading of functions. I have a function that returns different things depending of the value of a parameter. from typing import Literal, overload
@overload
def foo(return_type: Literal['dict'] = ...) -> dict: ...
@overload
def foo(return_type: Literal['list'] = ...) -> list: ...
def foo(return_type: Literal['dict', 'list'] = 'list') -> dict | list:
if return_type == 'dict':
return {}
else:
return [] So, with this code, I have an error saying the overload overlaps with an incompatible type. I get that the type is not compatible, but I do not get why it it saying that Maybe this is the wrong approach and I shouldn't overload by values, but I've done a lot of research and I can't find anything that could fit. I really hope someone can help me on this matter. Thanks ! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
The issue here is that both of your overloads have a default argument for the |
Beta Was this translation helpful? Give feedback.
The issue here is that both of your overloads have a default argument for the
return_type
parameter. That meansfoo()
(with no arguments) applies to both of them. To eliminate the overlapping overload and make the overloads match the implementation, you should delete the= ...
from the first overload.