pythonic way to free resources

Chirayu thephoenix235 at
Wed Aug 14 16:50:32 CEST 2002


I'm from the C++ world. I'm used to writing code like this.

// some block of code - could be try/catch, func body, loop body, etc
     ifstream inp (inFIle, ios::read | ios::binary)
     ofstream out (outFIle, ios::write | ios::binary)
     use inp and out

and be safe in the knowledge that if there were any any exceptions, there 
is no resource leak. For instance, if the output file cud'nt be opened, 
then the input file would be closed. if there was some error after both 
files were opened but in this block (assuming it was uncaught) - then both 
files will be closed.

What is the python idiom to do something like this?


More information about the Python-list mailing list