英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论