Skip to content

Commit

Permalink
Avoid stacktrace on process exit in Client.__del__()
Browse files Browse the repository at this point in the history
Client.close() may call ConnectionPool.release() or
ConnectionPool.disconnect(); both methods may end up calling
os.getpid() (through ConnectionPool._checkpid() or threading.Lock()
(through ConnectionPool.reset()). As mentioned in the Python
documentation [1], at interpreter shutdown, module globals (in this
case, the os and threading module references) may be deleted or set to
None before __del__() methods are called. This causes an
AttributeError to be raised when trying to run e.g. os.getpid(); while
the error is ignored by the interpreter, the traceback is still
printed out to stderr.

Closes #3014

[1] https://docs.python.org/3/reference/datamodel.html#object.__del__
  • Loading branch information
noirbee committed Oct 1, 2024
1 parent 2e46613 commit ae5b957
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion redis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,18 @@ def __exit__(self, exc_type, exc_value, traceback):
self.close()

def __del__(self):
self.close()
try:
self.close()
except AttributeError as exc:
if exc.name in ("getpid", "Lock"):
# cf https://github.com/redis/redis-py/issues/3014
# Most likely means the "os" or "threading" reference in
# connection.py was unloaded before this method was called; this
# can happen on process exit, cf the warning in
# https://docs.python.org/3/reference/datamodel.html#object.__del__
pass
else:
raise

def close(self):
# In case a connection property does not yet exist
Expand Down

0 comments on commit ae5b957

Please sign in to comment.