attrs – 如何验证一个Literal或None的实例

huangapple go评论61阅读模式
英文:

attrs - how to validate an instance of a Literal or None

问题

这是我所拥有的。我相信这里有两个问题 - Literal 和 None。

from attrs import frozen, field
from attrs.validators import instance_of

OK_ARGS = ['a', 'b']

@field
class MyClass:
    my_field: Literal[OK_ARGS] | None = field(validator=instance_of((Literal[OK_ARGS], None)))

错误:

TypeError: Subscripted generics cannot be used with class and instance checks

编辑: 我已经用一个自定义验证器制定了一个解决方法。虽然不太美观:

def _validator_literal_or_none(literal_type):
    def inner(instance, attribute, value):
        if (isinstance(value, str) and (value in literal_type)) or (value is None):
            pass
        else:
            raise ValueError(f'You need to provide a None, or a string in this list: {literal_type}')
    return inner
英文:

This is what I have. I believe there are two problems here - the Literal and the None.

from attrs import frozen, field
from attrs.validators import instance_of

OK_ARGS = ['a', 'b']

@field
class MyClass:
    my_field: Literal[OK_ARGS] | None = field(validator=instance_of((Literal[OK_ARGS], None)))

Error:

TypeError: Subscripted generics cannot be used with class and instance checks

Edit: I've made a workaround with a custom validator. Not that pretty however:

def _validator_literal_or_none(literal_type):
    def inner(instance, attribute, value):
        if (isinstance(value, str) and (value in literal_type)) or (value is None):
            pass
        else:
            raise ValueError(f'You need to provide a None, or a string in this list: {literal_type}')
    return inner

答案1

得分: 2

你不能对字面值(Literals)和None进行isinstance()检查,而is_instance验证器内部使用了它(它的使用早于那些类型功能)。虽然我们因其复杂性而一直抵制添加完整的类型语言实现,但如果你想提出一个问题来探讨是否值得专门为这些情况创建一个,那是值得考虑的。

英文:

You can’t do isinstance() checks on Literals/Nones and that’s what the is_instance Validator is using internally (it predates those typing features by far).

While we’ve resisted adding a complete implementation of the typing language due to its complexity, having one dedicated to such cases mind be worth exploring if you’d like to open an issue.

huangapple
  • 本文由 发表于 2023年2月19日 15:17:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定