You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现嵌套型合法数据的参数类型校验?

首先,你的核心需求是递归验证传入的items参数结构——只能是字符串、整数,或者由这两种类型及符合规则的嵌套列表组成的结构。Python的类型注解仅作为静态提示,不会自动执行运行时验证,因此需要自行实现验证逻辑。

解决方案1:直接在PList初始化方法中验证

无需额外封装类,编写递归验证函数后,在__init__中检查参数合法性:

def is_valid_items(value):
    # 检查是否为字符串或整数
    if isinstance(value, (str, int)):
        return True
    # 检查是否为列表,递归验证每个元素
    elif isinstance(value, list):
        return all(is_valid_items(item) for item in value)
    # 其他类型均不合法
    else:
        return False

class PList:
    def __init__(self, name: str, items):
        self.type = "list"
        self.name = name
        # 验证结构,不合法则抛出异常
        if not is_valid_items(items):
            raise ValueError("items必须是字符串、整数,或由这些类型及符合规则的嵌套列表组成的结构")
        self.items = items

# 合法测试示例
a = PList('asd', ['asd'])
b = PList('mixed', [1, 2, 'test', [[3], []]])

# 非法测试(执行会抛出ValueError)
# c = PList('invalid', [{}])
# d = PList('invalid_nested', ['test', [{}]])

解决方案2:用dataclass封装并验证

如果希望用ListItems类封装结构,可以在dataclass的__post_init__方法中添加验证逻辑,确保每次创建ListItems实例时自动检查:

from __future__ import annotations
from dataclasses import dataclass

def is_valid_items(value):
    if isinstance(value, (str, int)):
        return True
    elif isinstance(value, list):
        return all(is_valid_items(item) for item in value)
    else:
        return False

@dataclass(frozen=True, order=True)
class ListItems:
    items: list | str | int

    def __post_init__(self):
        if not is_valid_items(self.items):
            raise ValueError("items结构不符合要求:只能是字符串、整数或符合规则的嵌套列表")

class PList:
    def __init__(self, name: str, items: ListItems):
        self.type = "list"
        self.name = name
        self.items = items

# 合法测试示例
a = PList('asd', ListItems(['asd']))
b = PList('nested', ListItems([[1,2], 'hello', []]))

# 非法测试(执行会抛出ValueError)
# c = PList('invalid', ListItems([{}]))

补充说明

Python原生支持抽象类(通过abc模块),但你的需求是结构合法性验证而非强制子类实现方法,因此递归检查是更直接的方案。上述验证函数会递归遍历所有嵌套列表的元素,确保不存在字典、自定义对象等不符合要求的类型。

内容的提问来源于stack exchange,提问作者dokichan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 18:20:27