Read-only (covariant) list parameter annotations#1745
Merged
Conversation
Dr-Irv
requested changes
May 17, 2026
Collaborator
Dr-Irv
left a comment
There was a problem hiding this comment.
thanks. This looks like an interesting idea!
Dr-Irv
approved these changes
May 17, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
List[str]#153 (already closed but similar issues still exist)assert_type()to assert the type of any return value)Some pandas functions expect a list as argument but not any sequence. Because
listis invariant, parameters annotated withlist[float]will not acceptlist[int], for examlpe, even though we know that the list is read-only and will not be modified. To fix this, I propose the following trick using theCovariantListprotocol. This protocol can replacelistannotations in parameter positions (never use as a return type, instead keep usinglistthere).Note that this problem has manifested before and one trick you use today is to parametrize the list with a type variable that has an appropriate upper bound (for example you use
list[HashableT]where you want a list of hashable objects). This is cumbersome because for every type of list element, you'll need to define a corresponding type variable. Also, there are some places where a list of a very wide type like a union is still used (for examplelist[AggFuncTypeBase]inDataFrame.aggregate). All of these can be replaced with theCovariantListprotocol.In this PR I only introduce the protocol and change one method to use it to demonstrate its value. I think it would be better to incrementally use this protocol in follow up PR(s) for easier work and review. For example a PR could replace all
list[HashableT]andlist[Hashable]in parameter positions byCovariantList[Hashable]then other uses could be audited and changed in separate follow-up PRs.