Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Requesting backwards compatibility exception for change to allow_nan meaning in JSON encoding #244

Closed
mdickinson opened this issue May 12, 2024 · 2 comments

Comments

@mdickinson
Copy link
Member

mdickinson commented May 12, 2024

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

@gpshead
Copy link
Member

gpshead commented May 12, 2024

I added a suggestion on the PR.

@mdickinson
Copy link
Member Author

Thanks, @gpshead!

Let's close here - the suggestion from @gpshead would make a backwards compatibility exception unnecessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants