pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

Spurious bad-assignment error when assigning generic function results to class attributes

Open QEDady opened this issue 7 months ago • 4 comments

Describe the Bug

When assigning the result of a generic function to a class attribute, Pyrefly can fail with a spurious bad-assignment error if the function involves nested closures and Type Aliases.

Reproduction

import typing
from typing import Callable, TypeVar, reveal_type

T = TypeVar('T')
A = T | Callable[[], T]
B = A | list[T]

def bar(x: int) -> None:
    pass

def f(x: B[T], g: Callable[[T], None]) -> A[T]:
    def if_callable() -> T:
        r = x()  # pyrefly: ignore[not-callable]
        g(r)
        return r
    if callable(x):
        return if_callable
    elif isinstance(x, list):
        g(x[0])
        return x[0]
    else:
        g(x)
        return x

class Test:
    def __init__(self, arg: B[int]):
        self.foo = f(arg, bar) # Fails with `(() -> A) | (() -> int) | int` is not assignable to attribute `foo` with type `(() -> int) | int` [bad-assignment]
        reveal_type(self.foo)

def standalone(arg: B[int]):
    foo = f(arg, bar) # This works
    reveal_type(foo)

reveal_type diagnostics:

INFO revealed type: (() -> int) | int [reveal-type]

Details

It seems that in the class attribute case, Pyrefly goes into the function body to resolve the generics for the call. When checking the code, the call to x() (where we had to ignore the not-callable error) seems to cause some confusion. This breaks the generic resolution, making Pyrefly fall back to the raw alias A and generate the conflicting () -> A type.

It appears to be a limitation of generic solving. However, it is unclear why this wasn't reported as a bad-return-type inside the function itself instead of a bad-assignment at the use site. Additionally, it is confusing why this fails in the class attribute case but works perfectly in the standalone function case.

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeSIEAtsbgE4AuABA6cROgOYA66YduKizYdOTarUZMAwqihRU2WABomAFTYwAaqjqq6MAG4w5AfVbEYvXmqYBedZp10AFAHI1bgJS8AgvfUmAB8ZOQUlGABtSIBdVTUY3gAhAP8QqAg4BkiE6ywYMCZsXRd8RHF0Bi8mAFoAPiYAOVx0GEReJk6mYlQ4ODzMAqYwUvKknLimTnLZeUVYaITVZtaY6vqmXwn29C6mQcKIMFMAYzD5mBd1hrUdvb26APwrzoBibtIDMChScohOdD0KKAhg1M5zCKJXb3TqcFx0HzQmEGBgAVzouzoHS6RyY4PCsFKXjuMKYKPRuyOp3OEWxnRgGUOcA4WQwJ0u%2BFUGSyxLp9zh%2BEiAAY1nyHjA0RimIKRXyGXA2mKugLEaSyRKKdK8icFH11PAGCTOgcmKZTBwIAwzS4FVAwKpdNMmOMOAw1kb7rawIQwLhcAERo7VMUEUwlW8mAAxVDQOBMADuloAFkwAAYuF4bXzVEIZ64VKrBAup8RxkFMXrMgEXFj%2B1AMBh0CDYVEMGBp324EuJhgpizt9OZhqunPFpiRYqYGqV-7oKgwSpQtUGYxmfs2hnezuI3gm1lYOQtS6OsaRV3uvmdgMuINFXTVd5qJOZBP0ADW-SR6tXUHMmhc24gMoIBkF8PyEAwghQBQ7wAAqfAUPxMGgWB4PgeItJAnDovWEAtIQvDvAAyjA7ZJg2xBwIgAD01GgYhpCEPQnDUQu1GYLgJxwNRJyYf8OEMHh6DUcM9AVoYMYEu2vF8PxdC4S0TC4MQgktHABHoGQvYtDUxh0MyikONwIAAMyEAAjAATMZvCRDAdACPpUKougEj0G2U6YBABgnIJxgBG4s5Am4vAgjUBgAI6ot5MBTm%2BMCkNOJzsnqDhuPGujoCF6AgAAvsBqC%2BRAxiRtAMAUChOAECQ5C5UAA

(Only applicable for extension issues) IDE Information

No response

QEDady avatar Apr 23 '26 18:04 QEDady

Created a minimal repro and confirmed that this bug still exists

from typing import Callable, TypeVar, reveal_type

T = TypeVar('T')
A = T | Callable[[], T]
B = A | list[T]

def bar(x: int) -> None:
    pass

def f(x: B[T], g: Callable[[T], None]) -> A[T]:
    def if_callable() -> T:
        r = x()  # pyrefly: ignore[not-callable]
        g(r)
        return r
    if callable(x):
        return if_callable
    elif isinstance(x, list):
        g(x[0])
        return x[0]
    else:
        g(x)
        return x

# Class attribute case — should work but errors
class Test:
    def __init__(self, arg: B[int]):
        self.foo = f(arg, bar)
        reveal_type(self.foo)

# Standalone case — works fine
def standalone(arg: B[int]):
    foo = f(arg, bar)
    reveal_type(foo)

ERROR (() -> (() -> int) | int) | (() -> int) | int is not assignable to attribute foo with type (() -> int) | int [bad-assignment] --> repro.py:27:20 | 27 | self.foo = f(arg, bar)

INFO revealed type: (() -> int) | int [reveal-type] (class attribute — correct!) INFO revealed type: (() -> int) | int [reveal-type] (standalone — correct!)

Key observations:

  1. Both reveal_type calls show the correct resolved type (() -> int) | int, yet the class-attribute assignment still fires bad-assignment — pyrefly knows the right answer but errors anyway.
  2. The standalone case (local variable) resolves identically and works without error confirming the bug is specific to the class-attribute assignment path.
  3. The inferred "source" type in the error ((() -> (() -> int) | int) | (() -> int) | int) shows pyrefly failing to fully substitute T = int into the type alias A when computing the assignment source type for self.foo it recursively expands A[int] but leaves an inner A unresolved.

This appears to be a generic-solving code path difference between class attribute inference and local variable inference. Tagging @samwgoldman for routing. This seems to be the second issue where Pyrefly fails due to improper handling of Typevars, maybe we need to change our design / approach to handle them better.

NathanTempest avatar May 18 '26 17:05 NathanTempest

Hi @QEDady. I spent a bit of time looking into this, and I think the issue might actually be in the code itself.

You have:

T = TypeVar('T')
A = T | Callable[[], T]
B = A | list[T]

But I think you need to change the definition of B to provide the explicit type argument:

T = TypeVar('T')
A = T | Callable[[], T]
B = A[T] | list[T]

With that small change, Pyrefly does work in the expected way.

samwgoldman avatar May 19 '26 22:05 samwgoldman

Thanks @samwgoldman for the fix. This makes sense.

However, can you give more insight on how the attribute case is different than the normal variable case? It seems Pyrefly tries to infer the type of the attribute even if it is not annotated from the return type, then it goes into the function and checks the paths against the return type but somehow it fails with bad-assignment. Even with the bug in the code, I would expect it to fail with bad-return-type. WDYT?

QEDady avatar May 20 '26 07:05 QEDady

This seems to be fixed - I no longer see an error in the sandbox, and the two revealed types are identical.

rchen152 avatar Jun 12 '26 23:06 rchen152