Skip to content

Odd behavior of inference on generic types? #3998

Description

@dillydill123

Describe the Bug

from typing import reveal_type

class Box[T]:
    value: T

def f() -> Box[int]:
    x = Box()
    reveal_type(x)
    return x

def g() -> list[int]:
    # Type inferred as list[Unknown]
    x = list()  # Note: Using [] will raise 'implicit-any-empty-container'
    reveal_type(x)
    return x

def h() -> list[int]:
    # Type inferred as list[int] without reveal_type
    x = list()
    return x

pyrefly produces no errors, but reveals x as Box[Unknown]. To me, this feels off, similar to implicit-any-type-argument but not quite, since we are returning Box[Unknown] on declared type Box[int]. Possibly related, adding reveal_type changes what the sandbox and pyrefly infers:

Box[Unknown]
Image

Becomes Box[int] after commenting out reveal_type.
Image

Without reveal_type, the inferred type is Box[int]. Is this behavior intended? Inferring Box[int] from the return type alone (with no constraining use to go off of) seems a little loose but this is a extraordinary and unlikely example I suppose.

As a comparison, mypy --strict will report [var-annotated]:

test.py:7: error: Need type annotation for "x"  [var-annotated]
test.py:8: note: Revealed type is "test.Box[Any]"
test.py:12: error: Need type annotation for "x" (hint: "x: list[<type>] = ...")  [var-annotated]
test.py:13: note: Revealed type is "list[Any]"
Found 2 errors in 1 file (checked 1 source file)

Apologies if I've misunderstood something about this. Thanks for any explanation you can give.

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN2UYANxiooAfSbEYAHXRyAxlFRw4dAEIEA2gBUAuojl1jdIWICuMRHR1y5mGGDpgAFAEo6AWgB8G7awYDIxN8OgBeP3x3YONBETFJZhgXfDcYgRgGc0p0Onw7LEc6NncvXygIOAYtAKDckwBiGyTOdDAYSkFMOhU6CqqtAFV0AGt0XAB3dD100Ij%2BhlK6JoA5XAYrOkG4Vg4tPToJ6CgBVEqYOgByLmIKhQgGTwxSTxhuJk8FXHQGM-QOy7pOKiCRSZKpIGZbK5fLyQpOAAWpR8fUq1VqhnqxiaOharHanRg3V6CxqPwORwYCNw5n4wISYNm4VRVWiWIyWRyeRAABoQGRBGAoKRCAxaFAKE0AAqkQXCuhoLB4UJfNoQNjZVAMCDfQhyJoAZRgFwRDAYxDgiAA9FaBY5hYReGwrTB0FbMLgFHArarIBrKFqdW7nLwemZoKhsLA6L71Zrtd86LhiAn0HA9egyFTvp4RJQdomIjIQABmQgARgATMW5MRBHBMszi1VKBAFAxiyAAL581DtiAiABi0BgFEVOAIJHIXaAA

(Only applicable for extension issues) IDE Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions