8000 Support specification of `strict` on `Enum` type fields (#7761) · pydantic/pydantic@822e841 · GitHub
[go: up one dir, main page]

Skip to content

Commit 822e841

Browse files
Support specification of strict on Enum type fields (#7761)
1 parent 32ea570 commit 822e841

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

pydantic/_internal/_known_annotated_metadata.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
DATE_TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
3838
TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
3939
TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
40+
LAX_OR_STRICT_CONSTRAINTS = {*STRICT}
4041

4142
UNION_CONSTRAINTS = {'union_mode'}
4243
URL_CONSTRAINTS = {
@@ -85,6 +86,8 @@
8586
CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint].update(('url', 'multi-host-url'))
8687
for constraint in BOOL_CONSTRAINTS:
8788
CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint].update(('bool',))
89+
for constraint in LAX_OR_STRICT_CONSTRAINTS:
90+
CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint].update(('lax-or-strict',))
8891

8992

9093
def add_js_update_schema(s: cs.CoreSchema, f: Callable[[], dict[str, Any]]) -> None:

tests/test_types.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1700,6 +1700,28 @@ class Model(BaseModel):
17001700
]
17011701

17021702

1703+
def test_strict_enum() -> None:
1704+
class Demo(Enum):
1705+
A = 0
1706+
B = 1
1707+
1708+
class User(BaseModel):
1709+
model_config = ConfigDict(strict=True)
1710+
1711+
demo_strict: Demo
1712+
demo_not_strict: Demo = Field(strict=False)
1713+
1714+
user = User(demo_strict=Demo.A, demo_not_strict=1)
1715+
1716+
assert isinstance(user.demo_strict, Demo)
1717+
assert isinstance(user.demo_not_strict, Demo)
1718+
assert user.demo_strict.value == 0
1719+
assert user.demo_not_strict.value == 1
1720+
1721+
with pytest.raises(ValidationError, match='Input should be an instance of test_strict_enum.<locals>.Demo'):
1722+
User(demo_strict=0, demo_not_strict=1)
1723+
1724+
17031725
@pytest.mark.parametrize(
17041726
'kwargs,type_',
17051727
[

0 commit comments

Comments
 (0)
0