[Python-Dev] With statement

Duncan Booth duncan@rcp.co.uk
Thu, 6 Feb 2003 09:51:18 +0000


John Williams <jrw@pobox.com> wrote in news:3E414335.7030704@pobox.com:

> Why not combine the "with" and "local" statement ideas?  Change the 
> "with" statement so that there is no __enter__ method, and call __del__ 
> where there current proposal calls __exit__. 

If you put in your suggested check for getrefcount, then you can't port 
this to systems with no refcount (such as Jython) and this use of __del__ 
conflicts with Jython's use.

Also, if you try to reuse __del__ in this way you are introducing another 
possible place where it can go wrong (if someone has saved a reference to 
the controlled variable and your assertion fails), whereas with __exit__ 
you don't have to insist that all other references have gone.  

Indeed, if the variable is controlling a resource, such as a mutex, you 
might very well want to maintain a list of all controlled resources. The 
__exit__ can remove self from whatever data structures refer to it, but you 
would have to do it manually before letting the __del__ be called.

Finally consider:
   f = file(...)
   try:
     DoSomethingWith(f)
   finally:
     assert sys.getrefcount(f) == 2
     del f
     # f is guaranteed dead, so f.__del__ is called

If 'DoSomethingWith' throws an exception, the reference count for f is not 
2 as 'f' is still referred to from the stack backtrace that someone may 
wish to inspect.

-- 
Duncan Booth                                             duncan@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?