Skip to content

Commit

Permalink
move const validator to post validators. fixes pydantic#1410
Browse files Browse the repository at this point in the history
  • Loading branch information
selimb committed Apr 27, 2020
1 parent 529130f commit 82cd4b4
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 3 deletions.
1 change: 1 addition & 0 deletions changes/1410-selimb.md
@@ -0,0 +1 @@
Move `const` validator to post-validators so it validates the parsed value
2 changes: 1 addition & 1 deletion docs/usage/schema.md
Expand Up @@ -48,7 +48,7 @@ It has the following arguments:
* `title`: if omitted, `field_name.title()` is used
* `description`: if omitted and the annotation is a sub-model,
the docstring of the sub-model will be used
* `const`: this argument *must* have be the same as the field's default value if present
* `const`: this argument *must* be the same as the field's default value if present.
* `gt`: for numeric values (``int``, `float`, `Decimal`), adds a validation of "greater than" and an annotation
of `exclusiveMinimum` to the JSON Schema
* `ge`: for numeric values, this adds a validation of "greater than or equal" and an annotation of `minimum` to the
Expand Down
4 changes: 2 additions & 2 deletions pydantic/fields.py
Expand Up @@ -510,11 +510,11 @@ def populate_validators(self) -> None:
)
self.validators = prep_validators(v_funcs)

# Add const validator
self.pre_validators = []
self.post_validators = []

if self.field_info and self.field_info.const:
self.pre_validators = [make_generic_validator(constant_validator)]
self.post_validators.append(make_generic_validator(constant_validator))

if class_validators_:
self.pre_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and v.pre)
Expand Down
9 changes: 9 additions & 0 deletions tests/test_main.py
Expand Up @@ -383,6 +383,15 @@ class Model(BaseModel):
assert m.a == 3


def test_const_validates_after_type_validators():
# issue #1410
class Model(BaseModel):
a: int = Field(3, const=True)

m = Model(a="3")
assert m.a == 3


def test_const_with_wrong_value():
class Model(BaseModel):
a: int = Field(3, const=True)
Expand Down

0 comments on commit 82cd4b4

Please sign in to comment.