[英]Inheriting from a generic abstract class with a concrete type parameter is not enforced in PyCharm
背景:我正在使用 PyCharm 2019.1 和 Python 3.7
問題:我想創建一個泛型抽象 class,這樣當我從它繼承並將泛型類型設置為具體類型時,我希望繼承的方法能夠識別具體類型並在類型不匹配時顯示警告。
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 插件。
您的示例是顯式注釋靜默覆蓋基本 class 指定的類型的情況之一,即使在使用typing
模塊中的大寫List
和Dict
類型時也是如此。 它使用 Mypy 插件按預期引發錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.