diff --git a/CHANGES b/CHANGES index 20d7d8f51f..107e21a963 100644 --- a/CHANGES +++ b/CHANGES @@ -64,6 +64,7 @@ * Make `ClusterCommandsProtocol` an actual Protocol * Add `sum` to DUPLICATE_POLICY documentation of `TS.CREATE`, `TS.ADD` and `TS.ALTER` * Prevent async ClusterPipeline instances from becoming "false-y" in case of empty command stack (#3061) + * Close Unix sockets if the connection attempt fails. This prevents `ResourceWarning`s. (#3314) * 4.1.3 (Feb 8, 2022) * Fix flushdb and flushall (#1926) diff --git a/redis/connection.py b/redis/connection.py index 19263376d2..457e2b1896 100644 --- a/redis/connection.py +++ b/redis/connection.py @@ -920,7 +920,12 @@ def _connect(self): "Create a Unix domain socket connection" sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.socket_connect_timeout) - sock.connect(self.path) + try: + sock.connect(self.path) + except OSError: + # Prevent ResourceWarnings for unclosed sockets. + sock.close() + raise sock.settimeout(self.socket_timeout) return sock