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

Paul Moore p.f.moore at gmail.com
Thu Mar 24 14:30:38 EDT 2016


On 24 March 2016 at 18:02, Stephen J. Turnbull <stephen at xemacs.org> wrote:
>> I do it all the time in other languages when dealing with smallish
>  > files. Python's very nice file-object concept, slant toward
>  > iterator-based processing, and amazingly consistent ecosystem means
>  > that the same issues don't apply, so I'd rarely do the same
>  > thing. But for users migrating to Python from another language, or
>  > using Python occasionally while primarily using another language, I
>  > can see it being a lot more attractive.
>
> It occurs to me that we already have a perfectly appropriate builtin
> for the purpose anyway: print.  Add a filename= keyword argument, and
> make use of both file= and filename= in the same call an error.  If
> that's not the right answer, I don't see how str.to_file() can
> possibly be better.

Well, with print("A string", filename='foo.txt') what encoding should
be used? What if the user wants control of the encoding (on Windows,
it's far from uncommon to want UTF-8 instead of the system default,
for example)? What about error handlers? The same questions apply for
str.to_file() of course, although having extra arguments is likely to
be less of an issue there.

And yes, at some point the answer is "if the convenience function
doesn't suit your needs, you can fall back to explicit file handling".
But the trick is finding the *right* balance of convenience. And
having a "simple" way of writing a string to a file that doesn't at
least hint to the user that they should be thinking about encodings
seems to me like something of an attractive nuisance.

Paul


More information about the Python-ideas mailing list