From fdbd1de791e6fbf63a58f5aa29e095011743025c Mon Sep 17 00:00:00 2001 From: Shantanu Jain Date: Sun, 25 Oct 2026 14:58:15 -0700 Subject: [PATCH] Avoid repeated format of union members Codex claims this makes type checking pandas-stubs like 10% faster Co-authored-by Codex --- mypy/messages.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/mypy/messages.py b/mypy/messages.py index 0f3a5be368a4..83af360821b7 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -2678,7 +2678,14 @@ def format_list(types: Sequence[Type]) -> str: return ", ".join(format(typ) for typ in types) def format_union_items(types: Sequence[Type]) -> list[str]: - formatted = [format(typ) for typ in types if format(typ) != "None"] + formatted = [] + has_none = False + for typ in types: + item = format(typ) + if item == "None": + has_none = True + else: + formatted.append(item) if len(formatted) > MAX_UNION_ITEMS and verbosity == 0: more = len(formatted) - MAX_UNION_ITEMS // 2 formatted = formatted[: MAX_UNION_ITEMS // 2] @@ -2686,7 +2693,7 @@ def format_union_items(types: Sequence[Type]) -> list[str]: more = 0 if more: formatted.append(f"<{more} more items>") - if any(format(typ) == "None" for typ in types): + if has_none: formatted.append("None") return formatted