数据类继承:没有默认值的字段不能出现在有默认值的字段之后

zar*_*ski 10 python python-dataclasses

语境

我创建了两个数据类来处理表元数据。TableMetadata适用于任何类型的表,同时RestTableMetadata包含与从 REST api 提取的数据相关的信息

@dataclass
class TableMetadata:
    """
    - entity: business entity represented by the table
    - origin: path / query / url from which data withdrawn
    - id: field to be used as ID (unique)
    - historicity: full, delta
    - upload: should the table be uploaded
    """

    entity: str
    origin: str
    view: str
    id: str = None
    historicity: str = "full"
    upload: bool = True
    columns: list = field(default_factory=list)


@dataclass
class RestTableMetadata(TableMetadata):
    """
    - method: HTTP method to be used
    - payloadpath: portion of the response payload to use to build the dataframe
    """

    method: str
    payloadpath: str = None
Run Code Online (Sandbox Code Playgroud)

问题

由于继承的原因,method(没有默认值)出现在 后面columns,导致出现以下Pylance错误:Fields without default values cannot appear after fields with default values

我正在寻找一种方法来修复它而不覆盖__init__(如果有这样的方法)。我还注意到一个名为__init_subclass__此方法在类被子类化时调用。)的方法可能会影响如何RestTableMetadata.__init__生成其他子类。

zar*_*ski 7

这是 python > 3.10 的工作解决方案

@dataclass(kw_only=True)
class TableMetadata:
    """
    - entity: business entity represented by the table
    - origin: path / query / url from which data withdrawn
    - id: field to be used as ID (unique)
    - historicity: full, delta
    - upload: should the table be uploaded
    """

    entity: str
    origin: str
    view: str
    id: str = None
    historicity: str = "full"
    upload: bool = True
    columns: list = field(default_factory=list)


@dataclass(kw_only=True)
class RestTableMetadata(TableMetadata):
    """
    - method: HTTP method to be used
    - payloadpath: portion of the response payload to use to build the dataframe
    """

    method: str
    payloadpath: str = None
Run Code Online (Sandbox Code Playgroud)