如何将变量转换为数据类类型?

How to cast a variable to a dataclass type?

我想使用 dataclasses 模块中的函数 fields 但我的 IDE 一直警告我它应该只用于数据 classes (classes 或实例)。我知道可以忽略该警告,但我想将我的变量转换为 dataclass 类型,因为它更具可读性和 IDE 兼容性。

一个简单的例子:

from dataclasses import fields

all_fields = fields(some_instance) # Here I get a warning

上下文:

我想写一个 "mixin" class 来对我的数据 class 添加类型强制。示例:

from typing import Any
from dataclasses import fields, Field     

class TypedDCMixin:
    def __post_init__(self):
        self._check_fields_types()

    def _check_fields_types(self):
        for field in fields(self): # HERE I get the warning from my IDE 
            field_value = getattr(self, field.name)
            self._check_field_type(field, field_value)

    def _check_field_type(self, field: Field, field_value: Any):
        # whatever
        pass

相同的警告会出现在 dataclasses.fields 与未知数据 class 的参数一起使用的任何其他上下文中。

我通常通过使用函数 typing.cast 来避免这样的类型警告,但是没有 DataclassType 让我在警告行做 cast(DataclassType, self)

因此我的问题是:如何将变量转换为数据class 类型?

将 cast 与 dataclass 装饰器结合使用。

修改原始示例以添加转换:

from typing import Any, cast
from dataclasses import fields, Field, dataclass   

class TypedDCMixin:
    def __post_init__(self):
        self._check_fields_types()

    def _check_fields_types(self):
        for field in fields(cast(dataclass, self)): # Here the casting is used  
            field_value = getattr(self, field.name)
            self._check_field_type(field, field_value)

    def _check_field_type(self, field: Field, field_value: Any):
        # whatever
        pass