python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.56k stars 2.84k forks source link

Function declared to return list[int] actually returning list[Any] #17076

Open gjcarneiro opened 8 months ago

gjcarneiro commented 8 months ago

Bug Report

(A clear and concise description of what the bug is.)

To Reproduce

from typing import Any

def foo() -> list[int]:
    x: list[Any] = ["xxx"]
    return x

https://mypy-play.net/?mypy=latest&python=3.12&flags=strict%2Cdisallow-any-generics%2Cwarn-return-any&gist=35cfbe4d01eed0422eb72869846095c1

Expected Behavior

I would expect an error on line 6 return x. The function is declared to return list[int] but is returning list[Any].

Actual Behavior

No error.

$ mypy --strict --disallow-any-generics --warn-return-any  test.py 
Success: no issues found in 1 source file

Your Environment

erictraut commented 8 months ago

Mypy's behavior is correct and compliant with the Python typing spec. The type list[Any] is "consistent with" list[int] (or any other list). The Any type allows for "gradual typing". You can think of Any as "any type that could conceivably satisfy the type relationship".

gjcarneiro commented 8 months ago

And neither --disallow-any-generics or --warn-return-any triggers any kind of warning?... That's disappointing :disappointed:

JelleZijlstra commented 8 months ago

Eric is right in general, but I do think it's worth considering whether mypy's --warn-return-any option should have triggered here, which aims to cover this sort of issue. If you're interested, feel free to try making this change in a PR and we can see the fallout. (It might lead to an unacceptably high number of low-signal errors.)