Steven D'Aprano added the comment:
For starters, dunder names like __json__ are reserved for Python's own use, so
you would have to get the core developers to officially bless this use.
But... I'm not really sure that "the responsibility of determining how an
object should be represented in JSON objects firmly within the object itself"
is a good idea. For a general purpose protocol, I don't think you can trust any
object to return valid JSON. What if my object.__json__ returned "}key='c" or
some other invalid string? Whose responsibility is it to check that __json__
returns valid JSON?
I don't think there is any need to make this an official protocol. You know
your own objects, you know if you can trust them, and you can call any method
you like. So your example becomes:
my_json_string = json.dumps(
{'success': True, 'counter': object_counter.to_json()})
which is okay because that's clearly *your* responsibility to make sure that
your object's to_json method returns a valid string. If you make it an official
language wide protocol, it's unclear whose responsibility it is: the object
(dangerous!), the caller (difficult), the Python interpreter (unlikely),
json.dumps (unlikely).
----------
nosy: +steven.daprano
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue27362>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com