-
Notifications
You must be signed in to change notification settings - Fork 276
Closed
Labels
Description
Describe the Bug
Summary
Pyrefly reports a bad-return error when returning a list containing instances of subclasses, even when the return type is explicitly annotated as list[Base]. The inferred type list[A | B] should be assignable to list[Base] when both A and B inherit from Base.
Minimal Reproducible Example
from abc import ABC, abstractmethod
from typing import reveal_type
class Base(ABC):
@abstractmethod
def foo(self, x: int) -> None: ...
class A(Base):
def foo(self, x: int) -> None:
print(x)
class B(Base):
def foo(self, x: int) -> None:
pass
def return_object(name: str) -> list[Base]:
return [A()] + [B()]
def return_object_work_for_non_list(name: str) -> Base:
o = None
if name == "a":
o = A()
else:
o = B()
reveal_type(o)
return oActual Behavior
ERROR sandbox.py:21:12-23: Returned type `list[A | B]` is not assignable to declared return type `list[Base]` [bad-return]
Expected Behavior
No error. Since A and B are both subclasses of Base, the union A | B is a subtype of Base. While list is technically invariant, the list is created locally and immediately returned—there's no opportunity for type-unsafe mutation.
Mypy accepts this code without error.
Can we do something like if T is assignable to V then list[T] is assignable to list[V]?
Sandbox Link
(Only applicable for extension issues) IDE Information
No response
Reactions are currently unavailable