__del__ pattern?

bryanjugglercryptographer at yahoo.com bryanjugglercryptographer at yahoo.com
Tue Aug 16 19:12:32 CEST 2005

Tom Anderson wrote:
> On Mon, 15 Aug 2005, Chris Curvey wrote:
> > Is there a better pattern to follow than using a __del__ method?  I just
> > need to be absolutely, positively sure of two things:
> An old hack i've seen before is to create a server socket - ie, make a
> socket and bind it to a port:
> import socket
> class SpecialClass:
>  	def __init__(self):
>  		self.sock = socket.socket()
>  		self.sock.bind(("", 4242))
>  	def __del__(self):
>  		self.sock.close()
> Something like that, anyway.
> Only one socket can be bound to a given port at any time, so the second
> instance of SpecialClass will get an exception from the bind call, and
> will be stillborn. This is a bit of a crufty hack, though - you end up
> with an open port on your machine for no good reason.

Much worse, it's a bug. That pattern is for programs that need to
respond at a well-known port. In this case it doesn't work; the
fact that *someone* has a certain socket open does not mean that
this particular program is running.


More information about the Python-list mailing list