[Python-ideas] file(fn).read()
Chris Rebert
pyideas at rebertia.com
Sat Jun 13 12:44:33 CEST 2009
On Sat, Jun 13, 2009 at 1:25 AM, spir<denis.spir at free.fr> wrote:
> Hello,
>
> this post is half a question, half a proposal.
>
> Q: what happens to the filesystem file, and to the python file object below?
>
> text = file(fn).read()
>
> (used 'file' instead of 'open' in purpose)
> Note that there seemingly is no way to close or del the file object, nor even to check its 'closed' flag.
> I would expect that, in the case a file remains unnnamed, it is automatically closed and del-ed. If not, do you think it is sensible to ensure that?
Indeed, that is what happens. However, the language makes no
guarantees as to exactly *when* it will be GC-ed and closed; there's
nothing to ensure it will be closed in anything approaching a timely
manner, which could cause problems in the case of long-running
programs and/or programs that open many files.
It is true that for CPython, the file object will happen to be GC-ed
immediately, but this is mere implementation-specific behavior (due to
refcounting being employed) and probably ought not to be relied upon;
IronPython, for instance, does not behave the same way.
> In this case, we have a both safe and compact idiom to read file content. I consider this good, because the concept of "read file content" is both a single and simple operation -- and rather common.
Actually, we already have something for that. And it's only 1 extra line:
with f as file(fn):
text = f.read()
#when execution reaches here, the file is guaranteed to be closed
Though personally I think dealing with individual lines in a file is
more common than slurping in an entire file's contents all at once.
But I digress.
> Else, I would propose a pair of string methods (rather than 2 more builtin funcs) .filetext() & .filebytes(). In both cases, the target string is (supposed to be) a filename.
Probably unnecessary seeing as we have the above idiom.
> I take the opportunity to ask whether there is a chance in the future to be able to customize builtin types. (In this case many proposals on this list will simply vanish.)
I think you'll have to elaborate on what exactly you mean by
"customizing builtin types" for anyone to answer your question fully.
Assuming you mean "modify, replace, or extend in-place", I think the
prospects of that are rather grim; Python is not Ruby or Lisp.
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-ideas
mailing list