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

Émanuel Barry vgr255 at live.ca
Mon Mar 28 12:32:00 EDT 2016


On Mon, Mar 28, 2016 at 8:54 AM, Émanuel Barry < <mailto:vgr255 at live.ca> vgr255 at live.ca> wrote:

I wonder how reasonable it would be to add a new keyword to open that would .close() the file object upon a single write/read. Consider:

 

data = open("foo.txt", "r", close_after_use=True).read()

 

it makes it a tiny bit shorter than  using "with", but doesn't solve Nick's mental model issue -- the user still needs to be thinking about the fact that they are creating a file object and that it needs to be closed when you are done with it.

 

and I"m not sure how you would define "use" -- any i.o. opeartion? i.e.:

 

infile = open("foo.txt", "r", close_after_use=True)
first_line = infile.readline()

 

now what is the state of infile? a closed file object?

Sure. The keyword really could benefit from a better name, but it might solve some part of the issue. It doesn’t solve the mental model issue though, but to be fair, open() should always be wrapped in a context manager (IMO, anyway).

 

-Emanuel

 

exactly why context managers were introduced:

 

with open("foo.txt", "r", close_after_use=True) as infile:
    first_line = infile.readline()

something_else...

 

now it's pretty clear that infile is no longer a useful object.

 

-CHB

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160328/100f03ca/attachment-0001.html>


More information about the Python-ideas mailing list