Thanks to visit codestin.com
Credit goes to github.com

Skip to content

json.dump(..., default=something) takes a unary function but is documented binary #107544

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

Closed
RhysU opened this issue Aug 1, 2023 · 3 comments
Closed
Labels
docs Documentation in the Doc dir

Comments

@RhysU
Copy link

RhysU commented Aug 1, 2023

Documentation

TLDR

The following documentation at https://docs.python.org/3.13/library/json.html suggests that default should be a member method but light testing shows that it should be unary.

Documentation in Question

default(o)

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default() like this:

def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return json.JSONEncoder.default(self, o)

Light testing

The current documentation suggests the following pattern that never gets to TypeError("binary"):

import json

def binary(a, b):
    raise TypeError("binary")

# UNEXPECTED: TypeError: binary() missing 1 required positional argument: 'b'
json.dumps({"sample": object()}, default=binary)

A unary function behaves like I expect, namely entering unary(...):

import json

def unary(a):
    raise TypeError("unary")

# EXPECTED: TypeError: unary
json.dumps({"sample": object()}, default=unary)

Linked PRs

@RhysU RhysU added the docs Documentation in the Doc dir label Aug 1, 2023
@JelleZijlstra
Copy link
Member

The documentation you cite is for the default method of the JSONEncoder class, which indeed takes two arguments (self and the object).

The default argument for json.dumps is documented briefly under json.dump: https://docs.python.org/3.13/library/json.html#json.dump. That documentation could be more precise about the signature of the function.

@hugovk
Copy link
Member

hugovk commented Nov 9, 2023

Shall we backport the docs PR or are we ready to close this issue?

@ZeroIntensity
Copy link
Member

Let's close this. I think backporting is going to be too much of a pain due to how old the PR is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs Documentation in the Doc dir
Projects
Status: Done
Development

No branches or pull requests

4 participants