【问题标题】:Using mypy's generic self with python2 type comments将 mypy 的通用 self 与 python2 类型注释一起使用
【发布时间】:2020-01-06 10:31:22
【问题描述】:

我有一个案例,我想使用 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

如何将此代码转换为类型注释?类型 cmets 省略了 'self' 类型,因此 T 定义丢失:

    def set_scale(self, scale):
        # type: (float) -> T

【问题讨论】:

    标签: python python-2.7 types mypy type-hinting


    【解决方案1】:

    您没有排除self;您只需选择这样做:

    当使用简写形式时(例如# type: (str, int) -> None),除了实例和类方法的第一个参数(这些通常被省略,但这是允许的),每个参数都必须被考虑包括他们)。


    来自 PEP-484,Suggested Syntax for Python 2.7 and straddling code 末尾的第三个注释

    所以你可以写

    def set_scale(self, scale):
        # type: (T, float) -> T
    

    此类注释的使用者的工作是计算参数并确定self 是否被省略。

    【讨论】:

    • 完美!我应该考虑尝试一下。
    猜你喜欢
    • 2023-03-10
    • 2021-09-20
    • 1970-01-01
    • 2020-01-17
    • 2020-01-24
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2016-07-01
    相关资源
    最近更新 更多