On Sun, Aug 11, 2019 at 5:12 PM David Shawley <daveshawley@gmail.com> wrote:
1) Should JSONEncoder (the class underlying json.dumps) natively
support decimal.Decimal, and if so, can it avoid importing that module
unnecessarily?
I think yes on both counts :-)
2) Should there be a protocol obj.__json__() to return a string
representation of an object for direct insertion into a JSON file?

I'm inclined towards the protocol, since there are protocols for
various other encoders (eg deepcopy, pickle), and it avoids the
problem of json importing decimal. It can also be implemented entirely
as a third-party patch, although you'd need to subclass Decimal to add
that method.

I think if we ARE going to extend json to allow more flexibility, yes, a protocol would be a good way to do it.

But it makes me nervous -- I think the goal of the json module is to produce valid json, and nothing else. Opening up a protocol would allow users to fairly easily, and maybe inadvertently, create invalid JSON. I'm not sure there are compelling use cases that make that worth it.

-CHB

--
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython