Python code modernization, 5/n (#1165)

* Address raise-missing-from.

* Address simplifiable-if-expression.

* Address unnecessary-dunder-call.

* Address unnecessary-pass.

* Address use-list-literal.

* Address unused-variable.

* Address use-dict-literal.
This commit is contained in:
Felix Fontein
2025-10-12 16:02:27 +02:00
committed by GitHub
parent cad22de628
commit c75aa5dd64
66 changed files with 1549 additions and 1429 deletions
+5 -3
View File
@@ -227,18 +227,20 @@ class APIClient(_Session, DaemonApiMixin):
try:
version_result = self.version(api_version=False)
except Exception as e:
raise DockerException(f"Error while fetching server API version: {e}")
raise DockerException(
f"Error while fetching server API version: {e}"
) from e
try:
return version_result["ApiVersion"]
except KeyError:
raise DockerException(
'Invalid response from docker daemon: key "ApiVersion" is missing.'
)
) from None
except Exception as e:
raise DockerException(
f"Error while fetching server API version: {e}. Response seems to be broken."
)
) from e
def _set_request_timeout(self, kwargs):
"""Prepare the kwargs for an HTTP request by inserting the timeout
-1
View File
@@ -370,7 +370,6 @@ def _load_legacy_config(config_file):
}
except Exception as e: # pylint: disable=broad-exception-caught
log.debug(e)
pass
log.debug("All parsing attempts failed - returning empty config")
return {}
+1 -1
View File
@@ -106,7 +106,7 @@ class Context:
self.tls_cfg[name] = tls_cfg
def inspect(self):
return self.__call__()
return self()
@classmethod
def load_context(cls, name):
+1 -1
View File
@@ -71,7 +71,7 @@ class TLSConfig:
except ValueError:
raise errors.TLSParameterError(
"client_cert must be a tuple of (client certificate, key file)"
)
) from None
if not (tls_cert and tls_key) or (
not os.path.isfile(tls_cert) or not os.path.isfile(tls_key)
@@ -52,16 +52,16 @@ class NpipeHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
try:
conn = self.pool.get(block=self.block, timeout=timeout)
except AttributeError: # self.pool is None
raise urllib3.exceptions.ClosedPoolError(self, "Pool is closed.")
except AttributeError as exc: # self.pool is None
raise urllib3.exceptions.ClosedPoolError(self, "Pool is closed.") from exc
except Empty:
except Empty as exc:
if self.block:
raise urllib3.exceptions.EmptyPoolError(
self,
"Pool reached maximum size and no more connections are allowed.",
)
pass # Oh well, we'll create a new connection then
) from exc
# Oh well, we'll create a new connection then
return conn or self._new_conn()
@@ -141,7 +141,7 @@ class NpipeSocket:
@check_closed
def recv(self, bufsize, flags=0):
err, data = win32file.ReadFile(self._handle, bufsize)
dummy_err, data = win32file.ReadFile(self._handle, bufsize)
return data
@check_closed
@@ -163,7 +163,7 @@ class NpipeSocket:
try:
overlapped = pywintypes.OVERLAPPED()
overlapped.hEvent = event
err, data = win32file.ReadFile(
dummy_err, dummy_data = win32file.ReadFile(
self._handle, readbuf[:nbytes] if nbytes else readbuf, overlapped
)
wait_result = win32event.WaitForSingleObject(event, self._timeout)
@@ -159,16 +159,16 @@ class SSHConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
try:
conn = self.pool.get(block=self.block, timeout=timeout)
except AttributeError: # self.pool is None
raise urllib3.exceptions.ClosedPoolError(self, "Pool is closed.")
except AttributeError as exc: # self.pool is None
raise urllib3.exceptions.ClosedPoolError(self, "Pool is closed.") from exc
except Empty:
except Empty as exc:
if self.block:
raise urllib3.exceptions.EmptyPoolError(
self,
"Pool reached maximum size and no more connections are allowed.",
)
pass # Oh well, we'll create a new connection then
) from exc
# Oh well, we'll create a new connection then
return conn or self._new_conn()
+4 -4
View File
@@ -39,10 +39,10 @@ class CancellableStream:
def __next__(self):
try:
return next(self._stream)
except urllib3.exceptions.ProtocolError:
raise StopIteration
except socket.error:
raise StopIteration
except urllib3.exceptions.ProtocolError as exc:
raise StopIteration from exc
except socket.error as exc:
raise StopIteration from exc
next = __next__
+2 -2
View File
@@ -107,8 +107,8 @@ def create_archive(root, files=None, fileobj=None, gzip=False, extra_files=None)
try:
with open(full_path, "rb") as f:
t.addfile(i, f)
except IOError:
raise IOError(f"Can not read file in context: {full_path}")
except IOError as exc:
raise IOError(f"Can not read file in context: {full_path}") from exc
else:
# Directories, FIFOs, symlinks... do not need to be read.
t.addfile(i, None)
@@ -85,4 +85,4 @@ def split_buffer(stream, splitter=None, decoder=lambda a: a):
try:
yield decoder(buffered)
except Exception as e:
raise StreamParseError(e)
raise StreamParseError(e) from e
+2 -2
View File
@@ -420,10 +420,10 @@ def parse_bytes(s):
if suffix in units or suffix.isdigit():
try:
digits = float(digits_part)
except ValueError:
except ValueError as exc:
raise errors.DockerException(
f"Failed converting the string value for memory ({digits_part}) to an integer."
)
) from exc
# Reconvert to long for the final result
s = int(digits * units[suffix])