-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
List[subclass] is incompatible with List[superclass] #2984
Comments
This is as designed, please read up on Liskov. |
You can often use |
This is expected behavior and documented at http://mypy.readthedocs.io/en/latest/generics.html#variance-of-generic-types. Your example would fail with code like this:
If your function doesn't actually modify the list, you can get around this error by typing the argument as |
We need to ignore numpy and to heavily use assertions/exceptions to down-scope the types we actually use without violating the Liskov principle. This wouldn't be necessary if we had proper metaclasses :/ maybe we should look into ABC. The List[B] -> Sequence[B] changes are because Sequences, unlike Lists are covariant and allow specializing the type of their elements. This is WAI python/mypy#2984
@JelleZijlstra So how should one type hint a |
Old issue, but here is a solution that works: from typing import List, TypeVar
class Base:
pass
class Thing(Base):
pass
T = TypeVar("T", bound=Base)
def function(arg: List[T]) -> None:
pass
things: List[Thing] = [Thing()]
function(things) |
When a function that is accepting a list of a base class (for example
class Base
) is passed and argument which is a list of subclass instances of the base class (for exampleThing(Base)
) mypy complains about incompatible type:Error: Argument 1 to "function" has incompatible type List[Thing]; expected List[Base]
.Wrapping the argument with a cast to a list of the base class passes.
Code example:
The text was updated successfully, but these errors were encountered: