python / python/mypy

Ignore `str-format` error when object implements `__format__()` with custom type

Open
#17,951 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

I have inherited a project, where one class implements __format__(self, format_spec: str) -> str to implement a custom type for formatting. Running mypy on that code throws a false-positive error:

mypy-format.py:5 error: Unsupported format character "l" [str-format]

To Reproduce

class MyType:
    def __format__(self, format_spec: str) -> str:
        return "a" if format_spec == "l" else str(self)

print("{:l}".format(MyType()))

Expected Behavior

For a type implementing __format__ mypy/checkstrformat.py should not output any error.

Actual Behavior

mypy-format.py:5 error: Unsupported format character "l"  [str-format]

Your Environment

  • mypy 1.11.2 (compiled: yes)
  • Python 3.11.2

Links

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied Python reproduction with mypy 1.11.2, then inspect mypy/checkstrformat.py where the str-format error is reported. Trace how an object's format method is considered and ensure the example produces no unsupported-format error; confirm the behavior with the reproduction.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.