Closed
Description
The type of expression such as 1 if foo else 'x'
is object
(join of int
and str
). This is surprising and if such an expression is used in a union type context, the result is often not what's expected. Example:
from typing import Union
def f(x: Union[int, str]) -> None: ...
c = 1
f(1 if c else 'x') # Incompatible argument type "object"
This is also arguably inconsistent, as the or
and and
operators produce union types. For example, the type of (1+2) or 'x'
is Union[int, str]
.
Maybe conditional expressions should also produce unions? An alternative idea is to only produce union types if the type context is a union type, but this would be somewhat ad-hoc.
Activity
JukkaL commentedon Jun 1, 2017
cc @carljm
adsharma commentedon Jul 26, 2017
Comment related to #2464. The following shouldn't produce an error either.
If A and B have a common ancestor, it makes sense to use it. But if it turns out to be
builtins.object
it's probably a good signal that we have aNamedUnion
type of case where there are a couple of unrelated objects. So resolving to Union[A, B] makes more sense for that case?object
#3976JukkaL commentedon Nov 30, 2017
Bumped priority to high since the workaround is non-trivial and this seems to be affecting multiple users.
MentalMegalodon commentedon May 14, 2018
I'm working on this.
10 remaining items