mverleg / pyjson_tricks

Extra features for Python's JSON: comments, order, numpy, pandas, datetimes, and many more! Simple but customizable.
Other
154 stars 23 forks source link

Allow `cls=None` in `dump`, `dumps`, `load` and `loads` #79

Closed ruancomelli closed 4 years ago

ruancomelli commented 4 years ago

In the first place, thanks for this project! I'm using it for less than two hours and it already saved me from a lot of work.

One small thing that could improve the transition from json to json_tricks (at least in simple cases) is to allow cls=None in the main public functions defined by both libs, namely: dump, dumps, load and loads.

To provide a use case, I have some code that looks like this:

from json import dump
from pathlib import Path

def write_json(obj, path, cls=None):
    with Path(path).open('w') as file:
        dump(obj, file, indent=4, cls=cls)

obj = {'a': 0}
write_json(obj, 'path/to/myFile.json')

This code runs happily until I replace from json import dump with from json_tricks import dump, after what it raises a TypeError because None is not callable. This happens because in json_tricks.dump it is assumed that cls is an encoder. In json.dump, on the other hand, a None value is accepted, and in this case json.JSONEncoder is used.

I believe that a simple modification would allow a more seamless transition from json to json_tricks. We could rewrite

def dump(..., cls=TricksEncoder, ...):
    ...

as

def dump(..., cls=None, ...):
    if cls is None:
        cls = TricksEncoder
    ...

This way, the signature of json_tricks.dump would resemble more closely that of json.dump, and similar modifications could be applied to dumps, load and loads.

mverleg commented 4 years ago

Sorry I was moving and then the issue got buried. It seems like a good idea!

mverleg commented 4 years ago

New version with fix released (3.15.4)