On 7/26/2011 9:24 AM, Neil Cerutti wrote:
I use them all the time now, even when the resource being managed
is used for just one line, and never need be assigned an explicit
name. Is it good style, or annoying?

Annoying to you? or an actual or imagined audience?

     with open(in_fname, newline='') as in_file:
         folk = list(csv.DictReader(in_file))

This closes the file immediately.

The obvious alternative is:

     folk = list(csv.DictReader(open(in_fname, newline='')))

This happens to close the file immediately on current CPython since the file object is immediately deleted, but will not on some other implementations. If a process only opens a couple of files ever, that does not matter too much, although I believe the process shutdown procudure may warn about unclosed resources.

I sometimes do this, but know what is involved. That is partly habit.

With the many files I have to process, I find the with statements
create a visual structure that is helpful to track how many files
I'm working with at once.

If processing a directory of thousands of files, I would definitely use the with statement.

The existence of the context also usually forces me to think more
carefully about how long I really need that resource.

It definitely makes it easier to find file opens in the code, should you wish to revise. There is also an aesthetic quality to cleanly closing things as soon as possible.

But maybe I'm being a bit zeallous.

The stdlib test code has become zealous on this and other issues as it is intended to be usable by all conforming implementations. We need more zealous people like you to help with tests (and other code) ;-).

So I would stick with your style.

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to