Title: json - make load and dump work with filenames and path-like objects
Type: enhancement Stage: resolved
Components: Library (Lib) Versions: Python 3.9
Status: closed Resolution: duplicate
Dependencies: Superseder: Add support to load from paths to json.load
View: 36378
Assigned To: Nosy List: varunagrawal, xtreak
Priority: normal Keywords:

Created on 2019-07-18 05:03 by varunagrawal, last changed 2019-07-18 06:26 by varunagrawal. This issue is now closed.

Pull Requests
URL Status Linked Edit
PR 14832 closed varunagrawal, 2019-07-18 06:26
Messages (2)
msg348097 - (view) Author: Varun Agrawal (varunagrawal) * Date: 2019-07-18 05:03
Currently, json.load and json.dump take file pointers, aka file-like objects which have support for `.write()` and `.read()`. This necessitates the following pattern of code on a regular basis:

with open(filename) as f:
    o = json.load(f)
with open(filename, 'w') as f:
    json.dump(o, f)

While this is a fair pattern to live by, it would be nice for programmers to pass in the filename directly and let the functions handle opening and closing the file.

The way to do this would be to have a simple check if `fp` is a path-like object or a file-like object, and set up a context manager accordingly (using contextlib).
The original `load()` and `dump()` code definition can then be placed inside the context manager, which should make testing painless.

There might be an argument for this not being in alignment with duck-typing, but the overall benefits of this approach along with the ease afforded to programmers should make for a strong argument.
msg348098 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2019-07-18 05:08
This looks similar to issue36378 which was rejected and has a link to previous mailing list discussion.
Date User Action Args
2019-07-18 06:26:30varunagrawalsetpull_requests: + pull_request14624
2019-07-18 06:18:56serhiy.storchakasetstatus: open -> closed
superseder: Add support to load from paths to json.load
resolution: duplicate
stage: resolved
2019-07-18 05:08:57xtreaksetnosy: + xtreak
messages: + msg348098
2019-07-18 05:03:15varunagrawalcreate