python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.18k stars 2.78k forks source link

mypy silent about incorrect metaclasses-based protocol #4272

Open elazarg opened 6 years ago

elazarg commented 6 years ago
from typing import TypeVar, Type, Iterable, Iterator
T = TypeVar('T')
class M(type):
    def __iter__(self: Type[T]) -> Iterator[T]: raise Exception
class A(metaclass=M): pass
x: Iterable[A] = A  # fine
y: Iterable[str] = A  # should be rejected, but it is not

This pattern is important for enums, and came up in python/typeshed#1755. @ilevkivskyi noted that this is likely due to a bug in bind_self (see there).

ilevkivskyi commented 6 years ago

Thanks for opening the issue! It looks like the fix is more complex, since it requires carrying over original_type from subtypes.py.

elazarg commented 6 years ago

In general bind_self is buggy and ad-hoc. But when I tried to do it "right" it feels like it means making a class MemberChecker with all the context carried around by ExpressionChecker and TypeChecker.