Requesting backwards compatibility exception for change to allow_nan meaning in JSON encoding
Closed this issue · 2 comments
PR python/cpython#115246, targeting Python 3.14, is an enhancement to Python's json
module that allows the user to request that float infinities and NaNs be encoded to JSON null
. This addresses a fairly common feature request from users: the new behaviour matches the behaviour of JavaScript's JSON.stringify
, and there are situations where parity between JavaScript and Python is desirable. The new behaviour is triggered by the user specifying allow_nan='as_null'
in json.dump
or json.dumps
, or when creating an encoder using JSONEncoder
.
This is a backwards-incompatible change. In Python 3.13 and earlier versions, json.dump(my_obj, allow_nan='as_null')
will convert NaNs and infinities to unquoted strings NaN
, Infinity
, etc. in the output, purely because the string 'as_null'
is recognised as truthy. If PR #115246 were merged, json.dump(my_obj, allow_nan='as_null')
would instead convert NaNs and infinities to null
.
Per PEP 387, I'd like to request a Steering Council exception to the usual backwards compatibility rules: I believe that the "features no one could reasonably be depending on" clause applies here. The expected use of allow_nan
is to pass a boolean. I'd expect to find reasonable variations on this in the wild, including passing integers (e.g., 0
or 1
), None
, and instances of 3rd-party bool-like classes (e.g., np.bool_
), but I'd expect it to be rare to pass a string value for allow_nan
, and in particular it seems improbable that anyone is depending on the behaviour from passing the particular string "as_null"
to allow_nan
. Nevertheless, as a safety precaution, PR #115246 also introduces a DeprecationWarning
for cases where a user passes an instance of str
(other than the special 'as_null'
string).
Related discussion: https://discuss.python.org/t/harmonizing-the-json-serialization-of-non-finite-float-values-with-browsers-and-other-languages/20477
I added a suggestion on the PR.