diff --git a/mypy/checkstrformat.py b/mypy/checkstrformat.py index dcb711150870..1eed7e1fc4e4 100644 --- a/mypy/checkstrformat.py +++ b/mypy/checkstrformat.py @@ -18,8 +18,9 @@ from typing_extensions import Final, TYPE_CHECKING, TypeAlias as _TypeAlias from mypy.types import ( - Type, AnyType, TupleType, Instance, UnionType, TypeOfAny, get_proper_type, TypeVarType, - LiteralType, get_proper_types + Type, AnyType, TupleType, Instance, UnionType, TypeOfAny, get_proper_type, + TypeVarType, + LiteralType, flatten_nested_unions ) from mypy.nodes import ( StrExpr, BytesExpr, UnicodeExpr, TupleExpr, DictExpr, Context, Expression, StarExpr, CallExpr, @@ -353,9 +354,11 @@ def check_specs_in_format_call(self, call: CallExpr, if expected_type is None: continue - a_type = get_proper_type(actual_type) - actual_items = (get_proper_types(a_type.items) if isinstance(a_type, UnionType) - else [a_type]) + p_type = get_proper_type(actual_type) + if isinstance(p_type, UnionType): + actual_items = flatten_nested_unions(p_type.items, handle_type_alias_type=True) + else: + actual_items = [p_type] for a_type in actual_items: if custom_special_method(a_type, '__format__'): continue diff --git a/test-data/unit/check-formatting.test b/test-data/unit/check-formatting.test index 783c31c18770..8fc224f843e7 100644 --- a/test-data/unit/check-formatting.test +++ b/test-data/unit/check-formatting.test @@ -522,6 +522,19 @@ class D(bytes): '{}'.format(D()) [builtins fixtures/primitives.pyi] +[case testFormatCallFormatTypesUnionAliasWithCustomFormat] +from typing import Union + +class Date: + def __format__(self, spec: str) -> str: ... + +S = Union[str, bytes, Date] +s: Union[int, S] + +'{}'.format(s) # E: On Python 3 formatting "b'abc'" with "{}" produces "b'abc'", not "abc"; use "{!r}" if this is desired behavior +f'{s}' # E: On Python 3 formatting "b'abc'" with "{}" produces "b'abc'", not "abc"; use "{!r}" if this is desired behavior +[builtins fixtures/primitives.pyi] + [case testFormatCallFormatTypesBytesNotPy2] # flags: --py2 from typing import Union, TypeVar, NewType, Generic