Skip to content

T | None does not work when T is an union #20243

@Hakuyume

Description

@Hakuyume

Bug Report

mypy can not handle T | None when T is also an union.

To Reproduce

Run mypy on the following code.

def unwrap[T](value: T | None) -> T:
    assert value is not None
    return value


def f(value: int | str) -> None:
    pass


def main() -> None:
    value: int | str | None = 42
    f(unwrap(value))

https://mypy-play.net/?mypy=latest&python=3.12&gist=7c62868a7c9a0afc4853487fdd605f4b

Expected Behavior

mypy does not show any errors.
unwrap(value) converts int | str | None to int | str.

Actual Behavior

main.py:12: error: Argument 1 to "f" has incompatible type "object"; expected "int | str"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

mypy handles unwrap(value) as object and raises an error.

Your Environment

  • Mypy version used: 1.18.2
  • Mypy command-line flags: default of playground
  • Mypy configuration options from mypy.ini (and other config files): default of playground
  • Python version used: 3.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-join-v-unionUsing join vs. using unions

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions