Skip to content

Type of conditional expression is join instead of union #3487

Closed
@JukkaL

Description

@JukkaL

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions