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

ConstrainedFloat schema: differences between IEEE floats and json #1422

Merged
merged 9 commits into from Apr 30, 2020
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 changes/1417-vdwees.md
@@ -0,0 +1,3 @@
Modify schema constraints on `ConstrainedFloat` so that `exclusiveMinimum` and
minimum are not included in the schema if they are equal to `-math.inf` and
`exclusiveMaximum` and `maximum` are not included if they are equal to `math.inf`.
3 changes: 3 additions & 0 deletions pydantic/schema.py
Expand Up @@ -234,6 +234,9 @@ def get_field_schema_validations(field: ModelField) -> Dict[str, Any]:
f_schema['const'] = field.default
if field.field_info.extra:
f_schema.update(field.field_info.extra)
modify_schema = getattr(field.type_, '__modify_schema__', None)
if modify_schema:
modify_schema(f_schema)
return f_schema


Expand Down
10 changes: 10 additions & 0 deletions pydantic/types.py
@@ -1,3 +1,4 @@
import math
import re
import warnings
from decimal import Decimal
Expand Down Expand Up @@ -339,6 +340,15 @@ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
maximum=cls.le,
multipleOf=cls.multiple_of,
)
# Modify constraints to account for differences between IEEE floats and JSON
if field_schema.get('exclusiveMinimum') == -math.inf:
del field_schema['exclusiveMinimum']
if field_schema.get('minimum') == -math.inf:
del field_schema['minimum']
if field_schema.get('exclusiveMaximum') == math.inf:
del field_schema['exclusiveMaximum']
if field_schema.get('maximum') == math.inf:
del field_schema['maximum']

@classmethod
def __get_validators__(cls) -> 'CallableGenerator':
Expand Down
5 changes: 5 additions & 0 deletions tests/test_schema.py
@@ -1,3 +1,4 @@
import math
import os
import sys
import tempfile
Expand Down Expand Up @@ -1119,6 +1120,10 @@ class UserModel(BaseModel):
({'lt': 5}, float, {'type': 'number', 'exclusiveMaximum': 5}),
({'ge': 2}, float, {'type': 'number', 'minimum': 2}),
({'le': 5}, float, {'type': 'number', 'maximum': 5}),
({'gt': -math.inf}, float, {'type': 'number'}),
({'lt': math.inf}, float, {'type': 'number'}),
({'ge': -math.inf}, float, {'type': 'number'}),
({'le': math.inf}, float, {'type': 'number'}),
({'multiple_of': 5}, float, {'type': 'number', 'multipleOf': 5}),
({'gt': 2}, Decimal, {'type': 'number', 'exclusiveMinimum': 2}),
({'lt': 5}, Decimal, {'type': 'number', 'exclusiveMaximum': 5}),
Expand Down