On Tue, 13 Aug 2019 at 10:29, Richard Musil firstname.lastname@example.org wrote:
My goal is, as already mentioned:
To extend JSON encoder to support custom type to serialize into "JSON real number" (changed "fractional" to "real" to be aligned to Python source internal comment).
This includes support for decimal.Decimal, if it is the custom type the user chooses. I do not understand why you write that supporting Decimal is not my goal.
Support of *just* decimal provides custom type support:
class MyNumber: def serialise_to_string(self): ....
class MyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, MyNumber): return Decimal(obj.serialise_to_string())
json.dumps([MyNumber(), MyNumber()], cls=MyEncoder())
By limiting support to Decimal, we do the simplest thing that works, and we ensure that any custom classes get the benefit of having their string serialisation checked (if it can't be converted to Decimal, it's not going to be valid JSON) without the person implementing the custom class having to do anything. In fact, the custom class probably doesn't even have to implement custom JSON support at all, as it's quite likely that its normal str() representation is suitable to be passed to the Decimal constructor.
So defining a special protocol to allow JSON serialisation of numeric classes *other* than Decimal seems like a clear case of YAGNI. As the MyEncoder example above shows, support for Decimal allows the end user to define their own protocol if needed, so even "difficult" cases (should any exist, I can't think why they would) should be covered.
+1 on supporting Decimal, -1 on supporting anything more complex.