Skip to content

function returns Union[x,y] but it is expected to be 'x' always --- How to prevent 'x' is not compatible with 'y' #1355

Answered by erictraut
paxcodes asked this question in Q&A
Discussion options

You must be logged in to vote

If the function's return type depends on the type of one of the input parameters, the library author should provide @overload functions to differentiate them.

You have a few workarounds:

def my_func() -> A:
    a = some_third_party_func("some_value")
    assert isinstance(a, A)
    return a

or

def my_func() -> A:
    a = some_third_party_func("some_value")
    if isinstance(a, A):
        return a
    raise Exception("expecting a to be A")

or

def my_func() -> A:
    a = some_third_party_func("some_value")
    return cast(A, a)

I recommend the first option since it is safe but still relatively terse.

Note that isinstance(a, A) is not the same as type(a) == A. The function claims that it re…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by paxcodes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants