Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support specification of strict on Enum type fields #7761

Merged
merged 1 commit into from Oct 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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