Skip to content

Use more precise context for TypedDict plugin errors #18293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

brianschubert
Copy link
Collaborator

@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)

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