KEMBAR78
Use more precise context for TypedDict plugin errors by brianschubert · Pull Request #18293 · python/mypy · GitHub
Skip to content

Conversation

brianschubert
Copy link
Member

@brianschubert brianschubert commented Dec 13, 2024

Fixes #12271

Uses an applicable argument expression as the error context instead of the overall CallExpr.

Given:

# flags: --pretty --show-column-number
from typing import TypedDict

class A(TypedDict):
    x: int

a: A
x.setdefault("y", 123)
x.setdefault("x", "bad")

# Non-TypedDict case for reference
b: dict[str, int]
b.setdefault("x", "bad")

Before:

main.py:8:1: error: TypedDict "A" has no key "y"  [typeddict-item]
    a.setdefault("y", 123)
    ^~~~~~~~~~~~~~~~~~~~~~
main.py:9:1: error: Argument 2 to "setdefault" of "TypedDict" has incompatible type "str"; expected "int"  [typeddict-item]
    a.setdefault("x", "bad")
    ^~~~~~~~~~~~~~~~~~~~~~~~
main.py:13:19: error: Argument 2 to "setdefault" of "MutableMapping" has incompatible type "str"; expected "int"  [arg-type]
    b.setdefault("x", "bad")
                      ^~~~~
Found 3 errors in 1 file (checked 1 source file)

After:

main.py:8:14: error: TypedDict "A" has no key "y"  [typeddict-item]
    a.setdefault("y", 123)
                 ^~~
main.py:9:19: error: Argument 2 to "setdefault" of "TypedDict" has incompatible type "str"; expected "int"  [typeddict-item]
    a.setdefault("x", "bad")
                      ^~~~~
main.py:13:19: error: Argument 2 to "setdefault" of "MutableMapping" has incompatible type "str"; expected "int"  [arg-type]
    b.setdefault("x", "bad")
                      ^~~~~
Found 3 errors in 1 file (checked 1 source file)

@github-actions
Copy link
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@hauntsaninja hauntsaninja merged commit ce14043 into python:master Dec 14, 2024
19 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.

(🐞) Wrong column number for TypedDict.setdefault

2 participants