Bulletproof json.dump?

Chris Angelico rosuav at gmail.com
Mon Jul 6 09:51:36 EDT 2020


On Mon, Jul 6, 2020 at 11:39 PM Adam Funk <a24061 at ducksburg.com> wrote:
>
> Aha, I think the default=repr option is probably just what I need;
> maybe (at least in the testing stages) something like this:
>
> try:
>     with open(output_file, 'w') as f:
>         json.dump(f)
> except TypeError:
>     print('unexpected item in the bagging area!')
>     with open(output_file, 'w') as f:
>         json.dump(f, default=repr)
>
> and then I'd know when I need to go digging through the output for
> bytes, sets, etc., but at least I'd have the output to examine.
>

Easier:

def proclaimed_repr():
    seen = False
    def show_obj(obj):
        nonlocal seen
        if not seen:
            seen = True
            print("unexpected item in the bagging area!")
        return repr(obj)
    return show_obj

json.dump(f, default=proclaimed_repr())

If you don't care about "resetting" the marker, you can just use a
global or a default-arg hack:

def show_obj(obj, seen=[]):
    if not seen:
        seen.push(True)
        print("unexpected item in the bagging area!")
    return repr(obj)

json.dump(f, default=show_obj)

Either way, you can stick this function off in a utilities collection,
and then use it without fiddling with try/except.

ChrisA


More information about the Python-list mailing list