Skip to content

Commit

Permalink
Support specification of strict on Enum type fields (#7761)
Browse files Browse the repository at this point in the history
  • Loading branch information
sydney-runkle committed Oct 8, 2023
1 parent 32ea570 commit 822e841
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pydantic/_internal/_known_annotated_metadata.py
Expand Up @@ -37,6 +37,7 @@
DATE_TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
LAX_OR_STRICT_CONSTRAINTS = {*STRICT}

UNION_CONSTRAINTS = {'union_mode'}
URL_CONSTRAINTS = {
Expand Down Expand Up @@ -85,6 +86,8 @@
CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint].update(('url', 'multi-host-url'))
for constraint in BOOL_CONSTRAINTS:
CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint].update(('bool',))
for constraint in LAX_OR_STRICT_CONSTRAINTS:
CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint].update(('lax-or-strict',))


def add_js_update_schema(s: cs.CoreSchema, f: Callable[[], dict[str, Any]]) -> None:
Expand Down
22 changes: 22 additions & 0 deletions tests/test_types.py
Expand Up @@ -1700,6 +1700,28 @@ class Model(BaseModel):
]


def test_strict_enum() -> None:
class Demo(Enum):
A = 0
B = 1

class User(BaseModel):
model_config = ConfigDict(strict=True)

demo_strict: Demo
demo_not_strict: Demo = Field(strict=False)

user = User(demo_strict=Demo.A, demo_not_strict=1)

assert isinstance(user.demo_strict, Demo)
assert isinstance(user.demo_not_strict, Demo)
assert user.demo_strict.value == 0
assert user.demo_not_strict.value == 1

with pytest.raises(ValidationError, match='Input should be an instance of test_strict_enum.<locals>.Demo'):
User(demo_strict=0, demo_not_strict=1)


@pytest.mark.parametrize(
'kwargs,type_',
[
Expand Down

0 comments on commit 822e841

Please sign in to comment.