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