Skip to content

No TypeVar variable inference in ternary operators #18817

Open
@sasanjac

Description

@sasanjac

I have searched for a similar problem to reproduce but I haven't found anything, so:

I using a self-implemented monad which roughly looks as follows:

class Ok[T, E = None]:

    def __init__(self, value: T) -> None:
        self._value = value

class Err[E, T = None]: 

    def __init__(self, value: E) -> None:
        self._value = value

type Result[T, E] = Ok[T, E] | Err[E, T]

Now, inference of the second TypeVar variable works as intended, apart from the ternary operator.

Actual Behavior

class[U] Bar:
    def foo(data: U, cond: bool) -> Result[U, str]:
        return Ok(data) if cond else Err("Error")

results in

Incompatible return value type (got "Ok[U, str] | Err[str, None]", expected "Ok[U, str] | Err[str, U]")

Expected Behavior

def foo[U](data: U, cond: bool) -> Result[U, str]:
    if cond:
         return Ok(data)
     else
         return Err("Error")

and

def foo[U](data: U, cond: bool) -> Result[U, str]:
    if cond:
         return Ok(data)
    
     return Err("Error")

typecheck just fine.

Your Environment

  • Mypy version used:
    mypy 1.15.0 (compiled: yes)
  • Mypy command-line flags:
    none
  • Mypy configuration options from mypy.ini (and other config files):
  [tool.mypy]
    check_untyped_defs      = true
    disallow_any_unimported = true
    disallow_untyped_defs   = true
    follow_imports          = "normal"
    mypy_path               = "src"
    namespace_packages      = true
    no_implicit_optional    = true
    show_error_codes        = true
    strict_optional         = true
    warn_no_return          = true
    warn_redundant_casts    = true
    warn_return_any         = true
    warn_unused_ignores     = true
  • Python version used:
    Python 3.13.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions