Skip to content

Type of conditional expression is join instead of union #3487

Closed
@JukkaL

Description

@JukkaL
Collaborator

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

JukkaL commented on Jun 1, 2017

@JukkaL
CollaboratorAuthor
adsharma

adsharma commented on Jul 26, 2017

@adsharma

Comment related to #2464. The following shouldn't produce an error either.

class A:
    pass

class B:
    pass

class C:
    def __init__(self, a: A, b: B) -> None:
        if a and b:
            raise Exception("both a and b specified")

        if not a and not b:
            raise Exception("neither a nor b specified")

        self._obj: Union[A, B] = a if a else b
        reveal_type(a if a else b)

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 a NamedUnion type of case where there are a couple of unrelated objects. So resolving to Union[A, B] makes more sense for that case?

JukkaL

JukkaL commented on Nov 30, 2017

@JukkaL
CollaboratorAuthor

Bumped priority to high since the workaround is non-trivial and this seems to be affecting multiple users.

self-assigned this
on Feb 21, 2018
removed their assignment
on May 14, 2018
MentalMegalodon

MentalMegalodon commented on May 14, 2018

@MentalMegalodon
Contributor

I'm working on this.

10 remaining items

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @cjolowicz@adsharma@JukkaL@MentalMegalodon@SKHecht

        Issue actions

          Type of conditional expression is join instead of union · Issue #3487 · python/mypy