Is this overuse a context manager?

Ethan Furman ethan at stoneleaf.us
Tue Jul 26 20:08:38 CEST 2011


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?
> 
>     with open(in_fname, newline='') as in_file:
>         folk = list(csv.DictReader(in_file))
> 
> The obvious alternative is:
> 
>     folk = list(csv.DictReader(open(in_fname, newline='')))

I can see that it might take some getting used to, but I suspect the 
context managers are the better style: it clearly denotes the lifespan 
of the managed object, and provides for resource clean-up.  (I know, 
files are already automatically cleaned up -- at least in cpython; but 
not every managed object will be a file.)

~Ethan~



More information about the Python-list mailing list