如何强制数据类字段的类型?

时间:2019-11-22 10:26:45

标签: python python-3.x python-dataclasses

在此代码中:

import dataclasses

@dataclasses.dataclass
class MyClass:
    value: str

obj = MyClass(value=1)

使用不遵循MyClass类型的值实例化数据类value

是否存在一种简单的方法(使用装饰器,dataclass装饰器或库中的参数)来强制字段的类型,以便示例中的最后一行引发ValueError或类似的内容那?以这种方式执行类型是否有主要缺点?

1 个答案:

答案 0 :(得分:1)

您可以声明一个自定义的__post_init__方法(请参阅python's doc),然后将所有检查放在此处以强制进行类型检查。可以在父类中声明此方法以减少更改量。

import dataclasses


@dataclasses.dataclass()
class Parent:
    def __post_init__(self):
        for (name, field_type) in self.__annotations__.items():
            if not isinstance(self.__dict__[name], field_type):
                current_type = type(self.__dict__[name])
                raise ValueError(f"The field `{name}` was assigned by `{current_type}` instead of `{field_type}`")

        print("Check is passed successfully")


@dataclasses.dataclass()
class MyClass(Test):
    value: str


obj1 = MyClass(value="1")
obj2 = MyClass(value=1)

结果:

Check is passed successfully
Traceback (most recent call last):
  File "2.py", line 18, in <module>
    obj2 = MyClass(value=1)
  File "<string>", line 3, in __init__
  File "2.py", line 12, in __post_init__
    raise ValueError(f"The field `{name}` was assigned by `{current_type}` instead of `{field_type}`")
ValueError: The field `value` was assigned by `<class 'int'>` instead of `<class 'str'>`