Skip to content

Commit 18d21df

Browse files
committed
Cleanup ThreadPool with atexit rather than __del__
This removes the __del__ function from the generated Python client, and replaces it with a cleanup function. When a ThreadPool is created, the cleanup function is registered with the atexit module. This PR also allows the client to be used as a context manager, which will automatically clean up after itself rather than having to wait til process exit. This fixes issue kubernetes-client#1037, where the API client could hang indefinitely at garbage collection.
1 parent 5181d23 commit 18d21df

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

kubernetes/client/api_client.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
from __future__ import absolute_import
1212

13+
import atexit
1314
import datetime
1415
import json
1516
import mimetypes
@@ -77,18 +78,27 @@ def __init__(self, configuration=None, header_name=None, header_value=None,
7778
# Set default User-Agent.
7879
self.user_agent = 'OpenAPI-Generator/11.0.0-snapshot/python'
7980

80-
def __del__(self):
81+
def __enter__(self):
82+
return self
83+
84+
def __exit__(self, exc_type, exc_value, traceback):
85+
self.close()
86+
87+
def close(self):
8188
if self._pool:
8289
self._pool.close()
8390
self._pool.join()
8491
self._pool = None
92+
if hasattr(atexit, 'unregister'):
93+
atexit.unregister(self.close)
8594

8695
@property
8796
def pool(self):
8897
"""Create thread pool on first request
8998
avoids instantiating unused threadpool for blocking clients.
9099
"""
91100
if self._pool is None:
101+
atexit.register(self.close)
92102
self._pool = ThreadPool(self.pool_threads)
93103
return self._pool
94104

0 commit comments

Comments
 (0)