3

According to documentation, class serial.Serial() has the following methods.

close()
Close port immediately.

__del__()
Destructor, close port when serial port instance is freed.

I would like to know when I should use close() and __del__()? Example, I have a GUI that created an instance of serial.Serial() with an assigned port. According to documentation, the assigned port will be opened when the instance of serial.Serial(). Now when I terminate my GUI, am I correct to say that __del__() (and not close()) is the most appropriate method to use to close the serial port?

Sun Bear
  • 7,594
  • 11
  • 56
  • 102
  • 1
    When you terminate the GUI `__del__()` will be called automtically... – Stephen Rauch Feb 13 '19 at 07:50
  • @StephenRauch By any chance to you know where this instruction is stated in the serial.py module? I could not find it. Can you help show me the location of this instruction? – Sun Bear Feb 13 '19 at 08:36

1 Answers1

1

Analysis

If we look at pyserial source we see:

class SerialBase(io.RawIOBase):

Aha! Let's look into io.RawIOBase:

Base class for raw binary I/O. It inherits IOBase. There is no public constructor.

OK. Looking for __del__ in IOBase we see:

__del__() Prepare for object destruction. IOBase provides a default implementation of this method that calls the instance’s close() method.

Conclusion

You can use close() or del or with-context - they all close the port.

Alex Yu
  • 3,412
  • 1
  • 25
  • 38
  • Thank you. Noted that `.__del__()` method in the `serial.Serial()` object is really a method from python's `io.IOBase()` object. After reading other SO discussions on `__del__ ()`, e.g. [this](https://stackoverflow.com/questions/1481488/what-is-the-del-method-how-to-call-it) and [this](https://stackoverflow.com/questions/37852560/is-del-really-a-destructor), I learnt that [`__del__()` is really a Python Special Method name](https://docs.python.org/3/reference/datamodel.html#object.__del__) that is used to customize the finalization of a python object. – Sun Bear Feb 14 '19 at 13:57
  • 1
    The execution of `__del__()` can be problematic according to Python documentation. If so, I am thinking that in situations where I no longer require the port in an instance of the `serial.Serial()` object to be opened, I should promptly close the port using the `.close()` method instead of the `.__del__()` method. – Sun Bear Feb 14 '19 at 14:12
  • There is nothing problematic itself in calling `__methods__` - it's just looking strange to call them directly. E.g. `someobject.__del__()` instead of `del someobject` – Alex Yu Feb 14 '19 at 14:20
  • If you look at source you can also see `__exit__` method that automaticaly calls `close()`. So: call whatever you want - result will be same. – Alex Yu Feb 14 '19 at 14:33