PEP-442 - Python 3.4 and finalizations (__del__)

M

Marco Buttu

Hi all. Will the following code in Python 3.4 print "Goodbye from B()"
and "Goodbye from A():

class A:
def __init__(self, a):
self.a = a
print('In A.__init__()')
def __del__(self):
print('Goodbye from A()')

class B:
def __init__(self):
self.b = A(self) # Reference cycle
print('In B.__init__()')
def __del__(self):
print('Goodbye from B()')

b = B()
del b

Regards, Marco
 
S

Steven D'Aprano

Hi all. Will the following code in Python 3.4 print "Goodbye from B()"
and "Goodbye from A():

Perhaps you should try it and find out.


[steve@ando ~]$ python3.4 -E
Python 3.4.0a1+ (default:becbb65074e1, Aug 26 2013, 03:57:58)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux
Type "help", "copyright", "credits" or "license" for more information..... def __init__(self, a):
.... self.a = a
.... print('In A.__init__()')
.... def __del__(self):
.... print('Goodbye from A()')
........ def __init__(self):
.... self.b = A(self) # Reference cycle
.... print('In B.__init__()')
.... def __del__(self):
.... print('Goodbye from B()')
....In A.__init__()
In B.__init__()Goodbye from B()
Goodbye from A()
4


Does that answer your question?
 
M

Marco Buttu

Perhaps you should try it and find out.

Hi Steven, thanks for your answer. I tried it with Python 3.4a2, but I
did not see any output from __del__().
[steve@ando ~]$ python3.4 -E
Python 3.4.0a1+ (default:becbb65074e1, Aug 26 2013, 03:57:58)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux
Type "help", "copyright", "credits" or "license" for more information..... def __init__(self, a):
.... self.a = a
.... print('In A.__init__()')
.... def __del__(self):
.... print('Goodbye from A()')
........ def __init__(self):
.... self.b = A(self) # Reference cycle
.... print('In B.__init__()')
.... def __del__(self):
.... print('Goodbye from B()')
....In A.__init__()
In B.__init__()Goodbye from B()
Goodbye from A()
4

I thought in this case, the __del__() methods should have called
automatically...
Does that answer your question?

Yes, thanks a lot Steven, I saw the gc.collect() does not call the
__del__() method in Python 3.3, so I think I will look at the
documentation of gc in order to understand better. Thanks again, Marco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top