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

Chris Angelico rosuav at gmail.com
Mon Mar 28 11:55:38 EDT 2016


On Tue, Mar 29, 2016 at 2:45 AM, Chris Barker <chris.barker at noaa.gov> wrote:
> no, it's not. though now that think about it, while I understand that
> context managers are great as a universal and flexible way to ,well, mange
> context, for file objects themselves:
>
> open('a_file', 'w').write(some_stuff)
>
> Is really nice -- while we don't want to make reference-counting garbage
> collection a required part of the language in general, I wonder if it would
> be practical to make it part of the spec for SOME objects -- i.e kind of
> like you can define a given object to be a context manager, you could define
> certain objects to clean up after themselves when they go out of scope. It
> would sure be nice is this example ;; it would buy us that simple syntax,
> the atomic operation, etc...

The whole point of the context manager is that it defines the notion
"go out of scope". But if you want the simple syntax, the easiest way
is to create a helper:

def write_file(filename, contents):
    with open(filename, "w") as f:
        f.write(contents)

write_file('a_file', some_stuff)

Or, if you're writing a quick one-off script, just use the line you
have above, and don't worry about guaranteed closing. What's the worst
that can happen? AIUI buffered data will be written out at process
termination if not before, and of course the file will be closed. The
main case where you absolutely must close the file promptly is when
you plan to then open it again (in the same or another process), and a
quick script will usually know if that's going to be a possibility.

(How bad can it be? I suppose https://xkcd.com/292/ level bad. But not usually.)

ChrisA


More information about the Python-ideas mailing list