Ignore `str-format` error when object implements `__format__()` with custom type
Nobody has claimed this yet.
- 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
- #17714
- #11723
- How does type-checking work for
datetime.datetime, which implements a rich set of custom formatters? - string - Format Mini Language
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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