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

Conversation

kreathon
Copy link
Contributor

Motivation

This fix was motivated by the mypy_primer output for https://github.com/apache/spark/ in #11996.

Consider the following code:

Scalar = Union[
    int, float, bool, str, bytes, decimal.Decimal, datetime.date, datetime.datetime, None
]

x: Union[Scalar, "Series"]

'{}'.format(x)  

should lead to

On Python 3 formatting "b'abc'" with "{}" produces "b'abc'", not "abc"; use "{!r}" if this is desired behavior

Implementation

Ensure that the Union is flattened including type aliases before performing the follow checks (for the items):

for a_type in actual_items:
    if custom_special_method(a_type, '__format__'):
        continue
     self.check_placeholder_type(a_type, expected_type, call)
     self.perform_special_format_checks(spec, call, repl, a_type, expected_type)

Test Plan

Add [case testFormatCallFormatTypesUnionAliasWithCustomFormat]

@kreathon kreathon changed the title Fix format checking for unions with alias with custom format Fix format checking for Unions with alias with custom format Jan 23, 2022
@JelleZijlstra
Copy link
Member

I wonder if we should instead suppress this error when the operand is a Union. For other types (e.g. strs) adding !r changes behavior.

@kreathon
Copy link
Contributor Author

I agree that warnings should not give "unsafe" advises.

Alternatively, the warning could be updated for Union, because, in my opinion, is is really unlikely that the behavior is intended (for Unions).

@kreathon kreathon closed this Jan 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants