python - 类字段的类型注释

标签 python mypy

我正在尝试注释类字段,但 mypy (0.670) 未能在下面的代码中提出问题:

class X(object):
    x: int
    def __init__(self):
        self.x = "a"

x = X()

有没有办法使用 mypy 对类字段执行类型检查?如果没有,有没有办法在运行时轻松做到这一点?

最佳答案

最终使用 typeguard 模块编写了一个简单的运行时检查。

import typing
import typeguard

def check_class_hints(obj):
    hints = typing.get_type_hints(obj.__class__)
    for (name, hint_ty) in hints.items():
        val = getattr(obj, name)
        typeguard.check_type(name, val, hint_ty)

class X(object):
    x: int
    def __init__(self):
        self.x = "a"

x = X()
check_class_hints(x)

关于python - 类字段的类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56582487/

相关文章:

python - Mypy 似乎忽略了 TypeVar 类型的界限

python - mypy 如何忽略源文件中的一行?

Python 输入 : Concatenate sequences

具有派生类列表类型的类属性的 Python 类型注释

python - 存储日期 <= 最后 24 小时时 Django 返回计数

python - 如何在 Python 的 PyPyODBC 模块中使用 FetchAll?

python /珀尔 : timed loop implementation (also with microseconds)?

python - 在 numpy rearray 中查找接近的元素

代理后面的Python urllib urlretrieve

flask - 如何使用flask_sqlalchemy正确注释类型?