您可以像这样使用 ConstrainedStr 类型:
import pydantic
from typing import Set
MyUrlsType =pydantic.constr(regex="^[a-z]$")
class MyForm(pydantic.BaseModel):
urls : Set[MyUrlsType]
它仅在创建对象时起作用:
MyForm(urls={"a", "B"})
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
MyForm(urls={"a", "B"})
File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydantic\main.py", line 275, in __init__
values, fields_set, _ = validate_model(__pydantic_self__, data)
File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydantic\main.py", line 785, in validate_model
raise err
pydantic.error_wrappers.ValidationError: 1 validation error for MyForm
urls -> 1
string does not match regex "^[a-z]$" (type=value_error.str.regex; pattern=^[a-z]$)
在 Set add 方法上不强制 ConstrainedStr 类型:
f = MyForm(urls={"a", "b"})
>>> <MyForm urls={'b', 'a'}>
f.urls.add("c")
f.urls.add("yolo")
f.urls
>>> {'b', 'a', 'yolo', 'c'}