Python 类字段的类型注释
我试图注释类字段,但mypy(0.670)未能在下面的代码中提出问题:Python 类字段的类型注释,python,mypy,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_h
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)
最后使用
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)
没有Python3环境来测试atm,但是看起来部分文档可能是相关的。没有Python3环境来测试atm,但是看起来部分文档可能是相关的