python / python/mypy

Use empty outer context when checking str.format() calls

Open
#7,479 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-2-low
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

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

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.