-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Closed
Labels
Description
The type of the conditional expression 1 if foo else 'x'
is object
, which is totally unexpected.
To be consistent with the rest of the language, the type should be one of these:
Union[int, str]
(obvious)- Error, unless the type context is a supertype of both
int
andstr
. If one of the operands would have typeNone
, the type will always beOptional[...]
once mypy supports strict type checking ofNone
values (None
would be the only special case).
The rationale for case 2 is that mypy usually tries not to infer non-trivial union types, as these can result in confusing error messages far away from the source of the error. The error would be given if the only common non-union, non-Any supertype of the operands would be object
. This is a somewhat arbitrary heuristic, but it would probably work well in most cases.
(These are also sometimes called ternary expressions. -- SEO Guido)
leahein
Metadata
Metadata
Assignees
Labels
Projects
Milestone
Relationships
Development
Select code repository
Activity
JukkaL commentedon Mar 24, 2015
This was motivated by an example on the python-ideas mailing list.
gvanrossum commentedon Mar 24, 2015
What exactly is the context? Assuming the following two examples would work, (2) sounds good:
JukkaL commentedon Mar 25, 2015
Both would work. Examples of type context (yeah, this should be documented better):
x = expr
, the type context ofexpr
is the type ofx
(unless this assignment initializesx
).x = expr # type: T
, the type context ofexpr
isT
.f(expr)
, the type context ofexpr
is the type of the first argument off
.return expr
, the type context ofexpr
is the declared return type of the enclosing function.ilevkivskyi commentedon May 14, 2018
This is superseded by #3487