Delete a instance passed by reference into a method

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Dec 3 19:02:27 EST 2007


En Mon, 03 Dec 2007 19:53:20 -0300, sccs cscs <zorg724 at yahoo.fr> escribió:

> I am very surprising by the Python interpreter behavior : see code
> I initialize a 'A' and a 'B', and i give a B instance reference to the   
> instance A in 'm1' method. I can modify (IN/OUT mode)  the 'i'  
> attribute  (  aB.i = 10 ) , BUT I CANNOT DELETE "aB" into the fonction  
> m1 ! the code "     del aB " or " aB= None" has no effect. 'aB' still  
> exists when m1() is finsihed! WHY ? How can i do that?

First, read this <http://effbot.org/zone/python-objects.htm>


> class A(object):
>        def __init__(self):
>         pass
>     def m1 (self, aB ):
>         aB.i = 10
>         del aB
>         print "no more B"
> class B(object):
>     def __init__(self,i):
>         self.i = i
>     def __del__(self):
>         print "delete B"
>
> aA = A ()
> aB = B ( i = 6)
>
> unA.m1 (aB )
> print str( aB .i )  #--->  Display 10, aB is not destroy !

The "del" statement does NOT delete the object, it only removes the name  
 from the current namespace (and doing so, it decrements the object's  
reference count by one). If that was the last reference to the object, it  
becomes a candidate for being garbage collected later.

__del__ is not used too much. If you want to ensure resource deallocation,  
use either a try/finally block or a with statement:

f = open('filename'):
try
    for line in f:
      do_something_with(line)
finally
    f.close()

Another alternative, Python 2.5 and up:

 from __future__ import with_statement

with open('filename') as f:
    for line in f:
      do_something_with(line)
# there is an implicit f.close() here

If you want to use __del__ for another purpose, please describe your use  
case (what you want to achieve, not how you think you should implement it).

-- 
Gabriel Genellina




More information about the Python-list mailing list