-
Given something like this: From third-party lib from typing import Union
class A:
pass
class B:
pass
def some_third_party_func(param: str) -> Union[A,B]:
if ("some_value"):
return A()
else:
return B() My own function def my_func() -> A:
a = some_third_party_func("some_value") # I expect this to return 'A()' all the time
return a # Error: Expression of type A|B cannot be assigned to return type A How can I work around the error? I tried something like: def my_func() -> A:
a = some_third_party_func("some_value") # I expect this to return 'A()' all the time
if type(a) == A:
return a # Still gives the same error
raise Exception("expecting a to be A") Any advice? Full-context The library I'm working with is bs4. The function I am calling is |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
If the function's return type depends on the type of one of the input parameters, the library author should provide 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 |
Beta Was this translation helpful? Give feedback.
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:
or
or
I recommend the first option since it is safe but still relatively terse.
Note that
isinstance(a, A)
is not the same astype(a) == A
. The function claims that it re…