背景:我正在使用PyCharm 2019.1和Python 3.7
问题:我想创建一个泛型抽象类,这样当我从它继承并将泛型类型设置为具体类型时,我希望继承的方法识别具体类型,并在类型不匹配时显示警告。
带子类的泛型ABC
from abc import ABC, abstractmethod
from typing import TypeVar, Generic
T = TypeVar("T")
class FooGenericAbstract(ABC, Generic[T]):
@abstractmethod
def func(self) -> T:
pass
class Foo(FooGenericAbstract[dict]): # I am specifying T as type dict
def func(self) -> dict: # I would like the return type to show a warning, if the type is incorrect
pass
不正确类型没有警告
由于返回类型list
与具体类型参数dict
不匹配,因此这里可能会出现错误。
class Foo(FooGenericAbstract[dict]): # I am specifying T as type dict
def func(self) -> list: # Should be a warning here!
pass
from abc import ABC, abstractmethod
from typing import Dict, Generic, List, TypeVar
T = TypeVar("T")
class FooGenericAbstract(ABC, Generic[T]):
@abstractmethod
def func(self) -> T:
pass
class Foo(FooGenericAbstract[Dict[str, int]]):
def func(self) -> Dict[str, str]:
pass
对于coc.nvim和python 3.8,mypy 0.770会像预期的那样发出警告。
我想也许你应该使用类型提示而不是内置类型,因为mypy直到现在还不能识别内置类型。
PyCharm通常对类型提示的支持非常弱,因此建议您始终依赖JetBrains市场上提供的Mypy插件。
您的示例是这样一种情况,即显式注释静默地覆盖基类指定的类型,即使在使用typing
模块中的大写List
和Dict
类型时也是如此。它在使用Mypy插件时引发了一个预期的错误。