Skip to content

Issue #240: return default when passed float field is None #325

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ node_modules

# pyenv
.python-version
.venv

# Jet Brains
.idea
2 changes: 2 additions & 0 deletions flask_restx/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,8 @@ class Float(NumberMixin, Raw):

def format(self, value):
try:
if value is None:
return self.default
return float(value)
except (ValueError, TypeError) as ve:
raise MarshallingError(ve)
Expand Down
6 changes: 6 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,12 @@ def test_with_default(self):
assert not field.required
assert field.__schema__ == {"type": "number", "default": 0.5}

def test_default_on_none(self):
field = fields.Float(default=0.5)
assert not field.required
assert field.__schema__ == {"type": "number", "default": 0.5}
self.assert_field(field, None, 0.5)

@pytest.mark.parametrize(
"value,expected", [("-3.13", -3.13), (str(-3.13), -3.13), (3, 3.0),]
)
Expand Down