Skip to content

assignment to _ inside a function incorrectly becomes Any #17697

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

Open
DetachHead opened this issue Aug 21, 2024 · 2 comments
Open

assignment to _ inside a function incorrectly becomes Any #17697

DetachHead opened this issue Aug 21, 2024 · 2 comments
Labels
bug mypy got something wrong

Comments

@DetachHead
Copy link
Contributor

def foo() -> None:
    _ = [1] # error: no-any-expr

playground

@DetachHead DetachHead added the bug mypy got something wrong label Aug 21, 2024
@brianschubert
Copy link
Collaborator

To my understanding, this is caused by:

  1. Definitions of _ are treated as having an implicit type of Any (per here).
  2. mypy treats [1] as a call to a hidden def [T] (*T) -> list[T] function, where the type variable T needs to be resolved using the ordinary type inference rules.
  3. When inferring the type of a function, mypy prioritizes information from the type context. Here the type context says that the return type of the function needs to be compatible with Any. This ultimately causes mypy to prematurely resolve the type of the list constructor from def [T] (*T) -> list[T] to def (*Any) -> list[Any] on this line. Hence [1] is inferred to have type list[Any], cue the error.

I think this is the same underlying issue as #14664. In both cases, mypy infers the type of a callable to something overly broad when a type context is present, and infers a stricter type when the type context is removed.

@brianschubert
Copy link
Collaborator

Possible duplicate of #15253

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

2 participants