-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Use sequence instead of list #3119
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
This patch uses immutable sequence to ensure that List[Rules] is a valid type for _RuleList
Thanks. This makes sense, but it looks like it's a little more complicated than that. There's some code further down in this file that need changing but I'm not sure how exactly to fix it. |
The problem is that the isinstance in add_rules only checked for tuple and list and so there are possibly other Sequence types that can still get through. It might even be that only the isinstance with Sequence would be enough. Or a more defensive variant that checks if the rule is not an instance of Rule. I will leave that up to you, but I am happy to assist in any way! |
Union[ | ||
"Rule", | ||
List[Any], # Can't do detailed typechecking of lists. | ||
Sequence[Any], # Can't do detailed typechecking of lists. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What happens if we only change the outer List to Sequence? I don't think we need covariance on the inner List[Any]
, and then we wouldn't need to change the (tuple, list)
typecheck below. (Logically, this inner sequence is only supposed to be 2-, 3-, or 4-tuples. For historical reasons we also allow lists of the same lengths, but I don't see any reason to extend this to arbitrary sequences).
Changing the I think the real issue here is a minor confusion about typing. Users do something like this:
and mypy complains that
This makes sense because semantically, I think a better solution would be to make An additional note: the reason Sequence[T] is covariant in T is because Sequence instances are immutable. The suggestion emitted by mypy isn't that the type should be changed to sequence, it's that an immutable container type like Sequence should be used to facilitate covariance. I don't think we want this since
|
This patch uses immutable sequence to ensure that List[Rules] is a valid type for _RuleList
With the current typing it is not possible to correctly type code that uses List[Rule]. This is caused by the type annotation using
List[Union[Rule]]
which is not a superclass ofList[Rule]
. This is solved by using Sequence.This is also illustrated by:
When you run mypy on it, it will produce the following output: