Use empty outer context when checking str.format() calls
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
This is a follow up for https://github.com/python/mypy/pull/7418
Because mypy is still too eager about outer context and str.format() has object type for its arguments, passing a call to generic function as an argument to str.format() may cause false positives. For example:
'{:.3f}'.format(sum(list_of_floats))
Fails with
Incompatible types in string interpolation (expression has type "object", placeholder has type "Union[int, float]")
A more rectified test case:
[case testFormatCallGenerics]
from typing import TypeVar, Union
T = TypeVar('T')
def foo(x: T) -> Union[T, int]: ...
x: str
y: float
"{:.3f}".format(foo(x)) # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "Union[int, float]")
"{:.3f}".format(foo(y))
[builtins fixtures/primitives.pyi]
A potential simple fix is to re-accept the expression in empty context before checking the format specifier type.
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
Reproduce the behavior in the test case testFormatCallGenerics using the generic foo and str.format examples. Trace mypy's str.format call checking and its handling of outer context; done means the valid float formatting call no longer produces a false positive while the intended format-specifier error remains covered.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100