Spurious bad-assignment error when assigning generic function results to class attributes
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
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:
- Both
reveal_typecalls show the correct resolved type(() -> int) | int, yet the class-attribute assignment still firesbad-assignment— pyrefly knows the right answer but errors anyway. - The standalone case (local variable) resolves identically and works without error confirming the bug is specific to the class-attribute assignment path.
- The inferred "source" type in the error (
(() -> (() -> int) | int) | (() -> int) | int) shows pyrefly failing to fully substituteT = intinto the type aliasAwhen computing the assignment source type forself.fooit recursively expandsA[int]but leaves an innerAunresolved.
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.
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.
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?
This seems to be fixed - I no longer see an error in the sandbox, and the two revealed types are identical.