[英]Mypy annotation on a class decorator
我在Python中使用類裝飾器,無法確定為我的類賦予mypy滿意的類型注釋。
我的代碼如下:
from typing import Type
from pprint import pformat
def betterrepr(cls:Type[object]):
"""Improve representation of a class"""
class improved_class(cls): # line 12
def __repr__(self) -> str:
return f"Instance of {cls.__name__}, vars = {pformat(vars(self))}"
return improved_class
我目前遇到以下2個錯誤:
myprog.py:12:錯誤:類型“ cls”無效
myprog.py:12:錯誤:無效的基類
我應該對cls
的類型使用什么(順便說一句,對於用作參數的類使用此關鍵字是Pythonic嗎?)?
謝謝
mypy
當前不支持將函數參數用作基類。 唯一的選擇是使用以下type: ignore
使錯誤靜音type: ignore
注釋或偽別名(例如base: Any = cls
。
即使沒有注釋cls
, mypy
將正確地推斷出飾有一類的類型betterrepr
。 要記錄您的裝飾器返回的類與裝飾的類相似,請使用TypeVar
。
from typing import Type, TypeVar
from pprint import pformat
T = TypeVar('T')
def betterrepr(cls: Type[T]) -> Type[T]:
"""Improve representation of a class"""
class IClass(cls): # type: ignore
def __repr__(self) -> str:
return f"Instance of {cls.__name__}, vars = {pformat(vars(self))}"
return IClass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.