Skip to content

Sentinel and enum type merge issues with generic #22334

Open

Description

@cdce8p
from typing_extensions import sentinel

Undefined = sentinel("Undefined")

def none_if_undefined[_T](value: _T | Undefined) -> _T | None:
    return None if value is Undefined else value

def func() -> None:
    device_id: str | Undefined | None = Undefined
    device_id = none_if_undefined(device_id)  # <-- error
    reveal_type(device_id)
test.py:10: error: Argument 1 to "none_if_undefined" has incompatible type "str | Undefined | None"; expected "str | Undefined"  [arg-type]
test.py:11: note: Revealed type is "str | Undefined | None"

However, assigning the result from none_if_undefined to a temporary variable first works as expected.

def func() -> None:
    device_id: str | Undefined | None = Undefined
    x = none_if_undefined(device_id)
    reveal_type(x)
    device_id = x
    reveal_type(device_id)
test.py:11: note: Revealed type is "str | None"
test.py:13: note: Revealed type is "str | None"

--
A similar issues exists for enums

from enum import Enum
from typing import Literal

class E(Enum):
    SPECIAL = 1

def none_if_special[_T](value: _T | Literal[E.SPECIAL]) -> _T | None:
    return None if value is E.SPECIAL else value

def func() -> None:
    device_id: str | Literal[E.SPECIAL] | None = E.SPECIAL
    device_id = none_if_special(device_id)  # <-- error
    reveal_type(device_id)
test.py:12: error: Argument 1 to "none_if_special" has incompatible type "str | Literal[E.SPECIAL] | None"; expected "str | Literal[E.SPECIAL]"  [arg-type]
test.py:13: note: Revealed type is "str | Literal[test7.E.SPECIAL] | None"

--
For completeness the related example with just int - that works fine -- no errors.

def none_if_int[_T](value: _T | int) -> _T | None:
    return None if isinstance(value, int) else value

def func() -> None:
    device_id: str | int | None = 42
    device_id = none_if_int(device_id)
    reveal_type(device_id)

Activity

  1. cdce8p commented on Oct 30, 2026

    @cdce8p
    CollaboratorAuthor

    /CC @edgarrmondragon Interested in taking a look at that?

  2. edgarrmondragon commented on Oct 31, 2026

    @edgarrmondragon
    Contributor

    /CC @edgarrmondragon Interested in taking a look at that?

    Thanks for the ping! I'll take a look in the coming days.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions