Unclosed socket resource leak with ugly warnings in `-X dev` mode
During debugging sessions in PyCharm, which uses an older version of pydev (but the affected code parts are the same), when Python Development Mode is enabled, we get an ugly and discomforting ResourceWarning regarding an unclosed socket at the end of the debug session.
That socket was opened by pydev, as one can easily find out when additionally enabling tracemalloc stack frames.
It looks like this:

Or in text:
sys:1: ResourceWarning: unclosed <socket.socket fd=924, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 54549), raddr=('127.0.0.1', 54547)>
Object allocated at (most recent call last):
File "C:\Program Files\JetBrains\PyCharm 2020.3.3\plugins\python\helpers\pydev\pydevd.py", lineno 2173
main()
File "C:\Program Files\JetBrains\PyCharm 2020.3.3\plugins\python\helpers\pydev\pydevd.py", lineno 2055
dispatcher.connect(host, port)
File "C:\Program Files\JetBrains\PyCharm 2020.3.3\plugins\python\helpers\pydev\pydevd.py", lineno 1826
self.client = start_client(self.host, self.port)
File "C:\Program Files\JetBrains\PyCharm 2020.3.3\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_comm.py", lineno 439
s = socket(AF_INET, SOCK_STREAM)
Process finished with exit code -1
The affected socket is opened here with start_client():
https://github.com/fabioz/PyDev.Debugger/blob/018e137f7bc4cdd03a465e020833f2248ba5ddcc/pydevd.py#L2884
Reading on, one can easily see in the subsequent close() method that while the pydev thread is killed, the socket is not closed afterwards.
I added self.client.close() to the end of the close() method:
def close(self):
try:
self.reader.do_kill_pydev_thread()
except :
pass
self.client.close()
And with that it works fine now, without ugly ResourceWarning
Regards, Niels