Skip to content

Add __format__ overrides to complex, float, int, and str #14523

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

Merged
merged 1 commit into from
Aug 5, 2025

Conversation

brianschubert
Copy link
Member

These four builtins each define their own __format__ methods at runtime. While they all have the same signature as object.__format__, explicit overrides are needed so that type checkers resolve the right overrides in the presence of multiple inheritance.

Currently, type checkers incorrectly accept this code:

class Base:
    def __format__(self, format_spec: str) -> str: ...  # note: accepts keyword arguments

class Foo(int, Base): ...

# mypy:    ok
# pyright: ok
# PyCharm: ok
# runtime: TypeError: int.__format__() takes no keyword arguments
Foo().__format__(format_spec="02d")  

In particular, this affects enum.IntEnum/enum.StrEnum subclasses, which use int.__format__/str.__format__ at runtime, but type checkers think they use enum.Enum.__format__ (which, unlike the builtin __format__ methods, accepts keyword arguments).

Copy link
Contributor

github-actions bot commented Aug 4, 2025

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

@brianschubert
Copy link
Member Author

(for context, this was discovered as a common source of errors when running stubtest with python/mypy#19593)

@brianschubert brianschubert merged commit 953e21b into python:main Aug 5, 2025
63 checks passed
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