[Python-ideas] `to_file()` method for strings

Franklin? Lee leewangzhong+python at gmail.com
Fri Mar 25 12:30:19 EDT 2016


On Mar 24, 2016 10:22 PM, "Nick Coghlan" <ncoghlan at gmail.com> wrote:
> Independent of the "Why not just rely on the GC?" question, though,
> we're also forcing the user to upgrade their mental model to achieve
> their objective.
>
> User model: "I want to save this data to disk at a particular location
> and be able to read it back later"
>
> By contrast, unpacking the steps in the one-liner:
>
> - open the nominated location for writing (with implied text encoding
> & error handling)
> - write the data to that location
>
> It's that switch from a 1-step process to a 2-step process that breaks
> flow, rather than the specifics of the wording in the code (Python 3
> at least improves the hidden third step in the process by having the
> implied text encoding typically be UTF-8 rather than ASCII).
>
> Formulating the question this way does suggest a somewhat radical
> notion, though: what if we had a JSON-based save builtin that wrote
> UTF-8 encoded files based on json.dump()?

I was going to suggest that, if str save/load were to be implemented, it
could be made as a parallel to json.dump and json.load (as string module
members?). Any new features like atomicity would be "backported" to
json.dump/load. Same with pickle.load/dump. It's just str serialization,
isn't it?

If there is a save/load builtin (or dump/load), I don't see what's so
special about JSON. (YAML is more like Python, including in readability.)
I'd suggest that you can specify a "format" parameter (or with another
name) to use it with pickle, json, yaml, etc., but that means two ways of
doing things. Deprecate the original way?

    import json
    load("data.json", format=json)

Without a format kwarg, Python might look at the file extension and try to
guess the format. Modules could register extensions (is this magic?), or it
could look for an object with the same name which has __dump__/__load__ (is
this VERY magic?).

I don't like either: You have to import pickle to load it, but you wouldn't
have to name it explicitly to use it. I'd hate `import pickle;
pickle.register(".p")`: this thread is for scripters and not application
devs, so wordiness matters.

Your proposal means I don't even have to import json to use json, and json
needs explaining to a data scientist (who won't typically have web dev
experience).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160325/6ecbbf85/attachment.html>


More information about the Python-ideas mailing list