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

Allow type casting from strings to numerics #71

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
11 changes: 10 additions & 1 deletion lollipop/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,11 @@ class Any(Type):
class Number(Type):
"""Any number type (integer/float).

:param bool strict: If True, it will allow to perform type casting
from string representation to numeric. If False, it will raise
:exc:`~lollipop.errors.ValidationError` for strint input during
deserialization.

Error message keys:
* invalid - invalid value type. Interpolation data:
* data - actual value
Expand All @@ -173,6 +178,10 @@ class Number(Type):
'invalid': 'Value should be number',
}

def __init__(self, strict=True, *args, **kwargs):
super(Number, self).__init__(**kwargs)
self.strict = strict

def _normalize(self, value):
try:
return self.num_type(value)
Expand All @@ -183,7 +192,7 @@ def load(self, data, *args, **kwargs):
if data is MISSING or data is None:
self._fail('required')

if isinstance(data, string_types):
if self.strict and isinstance(data, string_types):
self._fail('invalid')

return super(Number, self).load(self._normalize(data), *args, **kwargs)
Expand Down
3 changes: 3 additions & 0 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,9 @@ def test_loading_integer(self):
def test_loading_float_value(self):
assert Number().load(1.23) == 1.23

def test_loading_non_strict_integer(self):
assert Number(strict=False).load("123") == 123

def test_loading_numeric_as_string(self):
with pytest.raises(ValidationError) as exc_info:
Number().load("123")
Expand Down