order of object desctruction

  • Thread starter Marcin Matuszkiewicz
  • Start date
M

Marcin Matuszkiewicz

Code

---------------------------------------------------------------------------
import socket

class xbert:
def __init__(self, name, host='127.0.0.1', port=1001):
self.name = name
self.host = host
self.port = port

self.SendCommand('%s New XgigBTS' % self.name)

def __del__(self):
print 'xbert destructor'
self.SendCommand('%s Exit' % self.name)

def SendCommand(self, cmd):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.host, self.port))
sock.send(cmd)
ret = sock.recv(pow(2,15))
sock.close()
return ret

def Version(self):
return self.SendCommand('Frunner Ver')

if __name__ == '__main__':
xb = xbert('xb')
print xb.Version()
---------------------------------------------------------------------------
Result

---------------------------------------------------------------------------
0::1.7.20030127.1340

xbert destructor
Exception exceptions.AttributeError: "'NoneType' object has no attribute
'socket'" in <bound method xbert.__del__ of <__main__.xbert instance at
0x007A9EC8>> ignored
---------------------------------------------------------------------------

From this example it seems that the instance of socket module is
destructed before instance of the xbert class. Is this interpretation
correct? This does not seem like a desired behavior. Is there a way
around it?

Thanks,

Marcin
 
B

bromden

please, read the warning here
http://www.python.org/doc/ref/customization.html

try declaring a global variable starting with an underscore (i
am not kidding) and see if it works then,

you can also try to secure yourself with a conditional:

def SendCommand(self, cmd):
if socket:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
...
 
B

bromden

this is really tricky,

if an imported module is still available within the __del__
method of some object seems to depend on implementation, version
and a bit of luck (then it's all about timing, i think),

so generally you should stick to the rule that "__del__()
methods should do the absolute minimum needed to maintain
external invariants" and use the conditional
 
M

Marcin Matuszkiewicz

I have moved a test of the xbert module to new file

import xbert

xb = xbert.xbert('xb')
print xb.Version()

And now there is no problem when calling __del__()

Marcin
 

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,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top