Skip to content

No TypeVar variable inference in ternary operators #18817

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:

classOk[T, E=None]:
def__init__(self, value: T) ->None:
self._value=valueclassErr[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:
deffoo(data: U, cond: bool) ->Result[U, str]:
returnOk(data) ifcondelseErr("Error")

results in

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

Expected Behavior

deffoo[U](data: U, cond: bool) ->Result[U, str]:
ifcond:
returnOk(data)
elsereturnErr("Error")

and

deffoo[U](data: U, cond: bool) ->Result[U, str]:
ifcond:
returnOk(data)
returnErr("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 = truedisallow_any_unimported = truedisallow_untyped_defs = truefollow_imports = "normal"mypy_path = "src"namespace_packages = trueno_implicit_optional = trueshow_error_codes = truestrict_optional = truewarn_no_return = truewarn_redundant_casts = truewarn_return_any = truewarn_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