The Decimal object subclasses Number which establishes an as_string constructor parameter in order to serialize values as strings.
While this is a good idea and probably caters to a canonical use-case in serialization, there is the potential for unexpected behaviour in deserialization and/or validation (when using the Decimal object, specifically).
Construction from an integer or a float performs an exact conversion of the value of that integer or float
From the Python documentation, even with as_string set, the current behaviour is to deserialize by passing directly to decimal.Decimal(), causing a situation like this:
This behaviour is at best arcane but at worst unexpected or wrong regardless of whether as_string is set.
I propose that when as_stringis set to true, either the _deserialize method implicitly casts the value to a string before passing to decimal.Decimal() or non-string values do not pass validation. Legacy behaviour would be preserved when as_string is false.
I prefer the implicit coercion to a string and can submit a small pull request to implement this. Failing validation is a bit more difficult because you have to differentiate between str and unicode - but I have presented it here as a potential solution to the problematic behaviour for comparison.
The text was updated successfully, but these errors were encountered:
The
Decimal
object subclassesNumber
which establishes anas_string
constructor parameter in order to serialize values as strings.While this is a good idea and probably caters to a canonical use-case in serialization, there is the potential for unexpected behaviour in deserialization and/or validation (when using the
Decimal
object, specifically).This is because the Python
decimal.Decimal()
method constructs values from integers, strings, floats, or tuples; and (per https://docs.python.org/2.7/library/decimal.html#quick-start-tutorial):From the Python documentation, even with
as_string
set, the current behaviour is to deserialize by passing directly todecimal.Decimal()
, causing a situation like this:This behaviour is at best arcane but at worst unexpected or wrong regardless of whether
as_string
is set.I propose that when
as_string
is set to true, either the_deserialize
method implicitly casts the value to a string before passing todecimal.Decimal()
or non-string values do not pass validation. Legacy behaviour would be preserved whenas_string
is false.I prefer the implicit coercion to a string and can submit a small pull request to implement this. Failing validation is a bit more difficult because you have to differentiate between
str
andunicode
- but I have presented it here as a potential solution to the problematic behaviour for comparison.The text was updated successfully, but these errors were encountered: