Classmethods in Generic Protocols with self-types, mypy type checking failure

江枫思渺然 提交于 2019-12-05 03:49:24

I'm not on expert on Mypy but have been teaching myself to use it recently and I think this may be due to an issue in Mypy mentioned here:

https://github.com/python/mypy/issues/3645

The issue is with handling TypeVar variables in class methods rather than anything directly to do with protocols.

The following minimal example is given in the link to show the problem.

T = TypeVar('T')

class Factory(Generic[T]):
    def produce(self) -> T:
        ...
    @classmethod
    def get(cls) -> T:
        return cls().produce()

class HelloWorldFactory(Factory[str]):
    def produce(self) -> str:
        return 'Hello World'

reveal_type(HelloWorldFactory.get())  # mypy should be able to infer 'str' here

The output from reveal_type is T rather than str. The same thing is happening with your code, where Mypy is failing to infer the type should be MyInteger rather than _P and so doesn't see your class as implementing the protocol. Changing the return type of the class methods to 'PType' makes the errors go away, but I'm not confident enough to know if there are any other impacts of that change.

There's been some discussion on how best to handle it, because it's not trivial to decide what the correct behaviour should be in every case, so might be no harm flagging this to them for more use case examples (see https://github.com/python/mypy/issues/5664 for example.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!