I'm pretty opposed to the idea of adding this functionality *specifically for 
JSON*, because JSON loading is not the only use case that could benefit from 
the convenience and reduced verbosity.

I propose the following (including type annotations and tests): 
https://repl.it/@maximum__/loadfile#main.py

Short version below:

    def loadfile(path, encoding='utf-8', loader=methodcaller('read')):
        """ Load data from a file, using a given "loader" """
        with open(path, 'r', encoding=encoding) as fp:
            return loader(fp)

So for the JSON use case, you would write:

    data = loadfile('data.json', loader=json.load)

This is still shorter and more readable than the with-open idiom, but also lets 
ANYONE benefit from the new convenience, including people who might want to 
load data from various other file formats (YAML, TOML, CSV, etc. etc. etc.) or 
even just plain Unicode or binary streams.

As a side effect, it also fixes the "what to call it" problem, and more 
importantly fixes the "how to delegate args to open() vs to json.load()" 
problem. loadfile() would pass along its kwargs to open(), and the user could 
use lambda, partial, or write a utility function to customize the loader itself.

If we are really really leery of adding a new top-level builtin, you could 
namespace it under a "loadfile" module:

    from loadfile import loadfile

Although having to explicitly import the thing somewhat cuts into the 
beginner-friendliness aspect.

-Greg Werbin
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/QXT5C7OFMCNPJL3QFN7GIP67DWUO7K32/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to