Skip to content

Fix format checking for Unions with alias with custom format #12044

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions mypy/checkstrformat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions test-data/unit/check-formatting.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down