Skip to content

Conditional expression type inference behaves unexpectedly #622

@JukkaL

Description

@JukkaL
Collaborator

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:

  1. Union[int, str] (obvious)
  2. Error, unless the type context is a supertype of both int and str. If one of the operands would have type None, the type will always be Optional[...] once mypy supports strict type checking of None 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)

Activity

JukkaL

JukkaL commented on Mar 24, 2015

@JukkaL
CollaboratorAuthor

This was motivated by an example on the python-ideas mailing list.

gvanrossum

gvanrossum commented on Mar 24, 2015

@gvanrossum
Member

What exactly is the context? Assuming the following two examples would work, (2) sounds good:

  • Using a type comment:
x = 'no' if a < 0 else sqrt(a)  # type: Union[str, float]
  • Using a pre-declared type:
x = Undefined(Union[str, float])
x = 'no' if a < 0 else sqrt(a)
JukkaL

JukkaL commented on Mar 25, 2015

@JukkaL
CollaboratorAuthor

Both would work. Examples of type context (yeah, this should be documented better):

  • In assignment x = expr, the type context of expr is the type of x (unless this assignment initializes x).
  • In assignment x = expr # type: T, the type context of expr is T.
  • In call f(expr), the type context of expr is the type of the first argument of f.
  • In return expr, the type context of expr is the declared return type of the enclosing function.
ilevkivskyi

ilevkivskyi commented on May 14, 2018

@ilevkivskyi
Member

This is superseded by #3487

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

        @JukkaL@gvanrossum@ilevkivskyi

        Issue actions

          Conditional expression type inference behaves unexpectedly · Issue #622 · python/mypy