使用带有 python2 类型注释的 mypy 的通用 self
Using mypy's generic self with python2 type comments
我有一个案例,我想使用 generic self 来用 mypy 打字。但是我需要保持 python 2.7 兼容性,所以我使用类型注释语法。
from typing import TypeVar
T = TypeVar('T', bound='Shape')
class Shape:
def set_scale(self: T, scale: float) -> T:
self.scale = scale
return self
如何将此代码转换为类型注释?类型注释省略了 'self' 类型,因此 T
定义丢失了:
def set_scale(self, scale):
# type: (float) -> T
您没有排除self
;您可以选择这样做:
When using the short form (e.g. # type: (str, int) -> None) every argument must be accounted for, except the first argument of instance and class methods (those are usually omitted, but it's allowed to include them).
From PEP-484, third note at the end of Suggested Syntax for Python 2.7 and straddling code
所以你可以这样写
def set_scale(self, scale):
# type: (T, float) -> T
这种评论的使用者的工作是计算参数并确定 self
是否被省略。
我有一个案例,我想使用 generic self 来用 mypy 打字。但是我需要保持 python 2.7 兼容性,所以我使用类型注释语法。
from typing import TypeVar
T = TypeVar('T', bound='Shape')
class Shape:
def set_scale(self: T, scale: float) -> T:
self.scale = scale
return self
如何将此代码转换为类型注释?类型注释省略了 'self' 类型,因此 T
定义丢失了:
def set_scale(self, scale):
# type: (float) -> T
您没有排除self
;您可以选择这样做:
When using the short form (e.g. # type: (str, int) -> None) every argument must be accounted for, except the first argument of instance and class methods (those are usually omitted, but it's allowed to include them).
From PEP-484, third note at the end of Suggested Syntax for Python 2.7 and straddling code
所以你可以这样写
def set_scale(self, scale):
# type: (T, float) -> T
这种评论的使用者的工作是计算参数并确定 self
是否被省略。