pythonic way to free resources

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Aug 15 11:42:43 CEST 2002


Chirayu <thephoenix235 at gmx.net> wrote in
news:mailman.1029350963.25717.python-list at python.org: 

> It seems I cant use try/except/finally. Its either try/finally or 
> try/except or nesting to get the desired effect. But even if it were 
> possible, its tough to write good stuff in the finally clause - if
> u're dealing with more than 1 resource.
> 
> try:
>     f1 = file (.......)
>     f2 = file (.......)
>     # some other processing - may throw
>     f3 = file (.......)
>     # more processing - may throw
> finally:
>     # which ones of f1, f2, f3 do i close?
> 
> I'm using files as a placeholder for a resource in general.  Any of
> the above lines may throw. Sorry, any of the above lines may raise an
> exception. 
> 
> I'm currently using
> f1,f2,f3 = None
> and then checking for None in the finally block. Not a nice solution.
> 
> 

I would write it thus:

>>> try:
	f = file('c:/temp/t.good')
	g = file('c:/temp/t.bad')
	h = file('c:/temp/t.ugly')
finally:
	try: h.close()
	except NameError: pass
	try: g.close()
	except NameError: pass
	f.close()

	
Traceback (most recent call last):
  File "<pyshell#18>", line 3, in ?
    g = file('c:/temp/t.bad')
IOError: [Errno 2] No such file or directory: 'c:/temp/t.bad'
>>> 

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list