How do I override PySerial's "__del__" method in Python?
Question: I have a simple Python script set up to send Characters to a device on COM3.
(This is running on Windows XP) The device receives the Characters fine, but
when the script ends, or I call

    
    
    ser.close()      #ser is an instance of the `serial` method `Serial`
    

It sets the DTR Line on the serial port High, Resetting my Device.

Perplexed by this, I poked around in the PySerial Documentation
(<http://pyserial.sourceforge.net/>) and found that the Module has a `__del__`
method, which calls the `ser.close()` function when the Serial instance is
deleted.

Is there anyway to Override this `__del__` method?

_(I would prefer to not have to disconnect the Reset Line of my device from
the DTR line)_

Below is the basic code I am using:

    
    
    import serial
    ser = serial.Serial()
    ser.port = 2      #actually COM3
    ser.baudrate = 9600
    ser.open()
    ser.write("Hello")
    ser.close()
    


Answer: Sure, go ahead and override it. You can either create a subclass of `Serial`
and specify a do-nothing `__del__()` method and use the subclass instead of
`Serial`, or delete that method from the actual `Serial` class (monkey-
patching) using the `del` statement. The former method is preferred but the
second may be necessary if code you don't have any control over is using the
serial port. Be sure the `__del__()` method doesn't do anything else important
before overriding it, of course.

Subclassing:

    
    
    import serial
    
    class mySerial(serial.Serial):
        def __del__(self):
            pass
    
    ser = mySerial()
    # rest of script the same
    

Monkey-patching:

    
    
    import serial
    
    del serial.Serial.__del__
    

If you have Python source for this module (i.e. it is not written in C), a
third approach would be to create your own copy of it and just edit it not to
do that. (You can also do this for C modules, but getting it running is a bit
more difficult if you don't have C expertise.)

Of course, changing the `__del__()` method to not call `ser.close()` isn't
going to help much in the code you give, since you're calling `ser.close()`
yourself. :-)

