ruff
ruff copied to clipboard
New Rule: Use `Sequence` instead of `list` to annotate arguments
Hi 👋🏻
Thanks for the amazing & blazing fast ecosystem 🫡
With the following code:
from pydantic import BaseModel
class Itembase(BaseModel):
title: str
class ItemRead(Itembase): ...
def my_util(Itembase): ...
items = [ItemRead(title"my title")]
my_utils(items) # 🚨 Type Error: `Type parameter "_T@list" is invariant, Consider switching from "list" to "Sequence" which is covariant`
I checked the typing module and found this quote:
Note that to annotate arguments, it is preferred to use an abstract collection type such as Sequence or Iterable rather than to use list or typing.List.
Hence, I'm raising an issue that'll enforce using Sequence
instead of list
If ruff can analyze the minimally needed types/methods for arguments and, based on that, suggests widening the type (for example, from list to Sequence), that would be amazing!
A blanket recommendation without some guard rails to replace list with Sequence would probably produce too many false positives.
Changing list
to Sequence
is often incorrect. MutableSequence
is less likely to be a problem, but even that can cause issue if you are relying on the sequence being an actual list somewhere else. This would be extremely disruptive in many code bases due to interactions with other code outside of someone's control (you can't call a function expecting a list when you only know it's a sequence, for example)