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

如何为attrs验证器中的attribute参数添加mypy类型注解?

attrs验证器中attribute参数的类型注解问题

原代码

from pathlib import Path

import attr


@attr.define(frozen=False)
class ExampleAtt:
    x: str = attr.field()

    @x.validator
    def check(self, attribute: attr.Attribute, value: str) -> None:
        expected_values = ['a', 'b', 'c']
        if value not in expected_values:
            raise ValueError('error')

遇到的错误

运行mypy时触发如下错误:

error: Missing type parameters for generic type "Attribute"  [type-arg]

问题

请问如何为attrs验证器中使用的attribute参数添加正确的类型注解?我已经尝试了上述代码中的写法,以及通过type(attribute)得到的attr._make.Attribute,但都无法解决问题。


解决方案

attr.Attribute是泛型类型,必须指定对应的类型参数才能通过mypy的类型检查,以下是两种可行的解决方式:

1. 匹配字段的具体类型

字段x的类型为str,因此可以将Attribute的泛型参数指定为str:

from pathlib import Path

import attr
from attr import Attribute


@attr.define(frozen=False)
class ExampleAtt:
    x: str = attr.field()

    @x.validator
    def check(self, attribute: Attribute[str], value: str) -> None:
        expected_values = ['a', 'b', 'c']
        if value not in expected_values:
            raise ValueError('error')

2. 使用Any兼容任意字段类型

如果不需要对字段类型做严格限定,可以用typing.Any作为泛型参数:

from pathlib import Path
from typing import Any

import attr
from attr import Attribute


@attr.define(frozen=False)
class ExampleAtt:
    x: str = attr.field()

    @x.validator
    def check(self, attribute: Attribute[Any], value: str) -> None:
        expected_values = ['a', 'b', 'c']
        if value not in expected_values:
            raise ValueError('error')

注意:不要使用attr._make.Attribute,这类带下划线的模块属于attrs的内部实现,版本更新时可能会被修改,导致代码兼容性问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:05:05