Python code modernization, 4/n (#1162)

* Address attribute-defined-outside-init.

* Address broad-exception-raised.

* Address broad-exception-caught.

* Address consider-iterating-dictionary.

* Address consider-using-dict-comprehension.

* Address consider-using-f-string.

* Address consider-using-in.

* Address consider-using-max-builtin.

* Address some consider-using-with.

* Address invalid-name.

* Address keyword-arg-before-vararg.

* Address line-too-long.

* Address no-else-continue.

* Address no-else-raise.

* Address no-else-return.

* Remove broken dead code.

* Make consider-using-f-string changes compatible with older Python versions.

* Python 3.11 and earlier apparently do not like multi-line f-strings.
This commit is contained in:
Felix Fontein
2025-10-11 23:06:50 +02:00
committed by GitHub
parent 33c8a49191
commit cad22de628
59 changed files with 556 additions and 630 deletions
+16 -13
View File
@@ -125,19 +125,22 @@ def create_archive(root, files=None, fileobj=None, gzip=False, extra_files=None)
def mkbuildcontext(dockerfile):
f = tempfile.NamedTemporaryFile()
t = tarfile.open(mode="w", fileobj=f)
if isinstance(dockerfile, io.StringIO):
raise TypeError("Please use io.BytesIO to create in-memory Dockerfiles")
elif isinstance(dockerfile, io.BytesIO):
dfinfo = tarfile.TarInfo("Dockerfile")
dfinfo.size = len(dockerfile.getvalue())
dockerfile.seek(0)
else:
dfinfo = t.gettarinfo(fileobj=dockerfile, arcname="Dockerfile")
t.addfile(dfinfo, dockerfile)
t.close()
f.seek(0)
f = tempfile.NamedTemporaryFile() # pylint: disable=consider-using-with
try:
with tarfile.open(mode="w", fileobj=f) as t:
if isinstance(dockerfile, io.StringIO):
raise TypeError("Please use io.BytesIO to create in-memory Dockerfiles")
if isinstance(dockerfile, io.BytesIO):
dfinfo = tarfile.TarInfo("Dockerfile")
dfinfo.size = len(dockerfile.getvalue())
dockerfile.seek(0)
else:
dfinfo = t.gettarinfo(fileobj=dockerfile, arcname="Dockerfile")
t.addfile(dfinfo, dockerfile)
f.seek(0)
except Exception: # noqa: E722
f.close()
raise
return f
+1 -2
View File
@@ -68,8 +68,7 @@ def home_dir():
"""
if IS_WINDOWS_PLATFORM:
return os.environ.get("USERPROFILE", "")
else:
return os.path.expanduser("~")
return os.path.expanduser("~")
def load_general_config(config_path=None):
@@ -17,23 +17,6 @@ from .. import errors
from . import utils
def check_resource(resource_name):
def decorator(f):
@functools.wraps(f)
def wrapped(self, resource_id=None, *args, **kwargs):
if resource_id is None and kwargs.get(resource_name):
resource_id = kwargs.pop(resource_name)
if isinstance(resource_id, dict):
resource_id = resource_id.get("Id", resource_id.get("ID"))
if not resource_id:
raise errors.NullResource("Resource ID was not provided")
return f(self, resource_id, *args, **kwargs)
return wrapped
return decorator
def minimum_version(version):
def decorator(f):
@functools.wraps(f)
+5 -6
View File
@@ -90,9 +90,8 @@ def split_port(port):
if external is not None and len(internal) != len(external):
raise ValueError("Port ranges don't match in length")
return internal, external
else:
if not external:
external = [None] * len(internal)
elif len(internal) != len(external):
raise ValueError("Port ranges don't match in length")
return internal, [(host, ext_port) for ext_port in external]
if not external:
external = [None] * len(internal)
elif len(internal) != len(external):
raise ValueError("Port ranges don't match in length")
return internal, [(host, ext_port) for ext_port in external]
+3 -5
View File
@@ -111,8 +111,7 @@ def frames_iter(socket, tty):
"""
if tty:
return ((STDOUT, frame) for frame in frames_iter_tty(socket))
else:
return frames_iter_no_tty(socket)
return frames_iter_no_tty(socket)
def frames_iter_no_tty(socket):
@@ -194,7 +193,6 @@ def demux_adaptor(stream_id, data):
"""
if stream_id == STDOUT:
return (data, None)
elif stream_id == STDERR:
if stream_id == STDERR:
return (None, data)
else:
raise ValueError(f"{stream_id} is not a valid stream")
raise ValueError(f"{stream_id} is not a valid stream")
+9 -11
View File
@@ -75,10 +75,9 @@ def compare_version(v1, v2):
s2 = StrictVersion(v2)
if s1 == s2:
return 0
elif s1 > s2:
if s1 > s2:
return -1
else:
return 1
return 1
def version_lt(v1, v2):
@@ -250,7 +249,7 @@ def parse_host(addr, is_win32=False, tls=False):
# These protos are valid aliases for our library but not for the
# official spec
if proto == "http" or proto == "https":
if proto in ("http", "https"):
tls = proto == "https"
proto = "tcp"
elif proto == "http+unix":
@@ -273,12 +272,11 @@ def parse_host(addr, is_win32=False, tls=False):
raise errors.DockerException(
f"Invalid bind address format: no path allowed for this protocol: {addr}"
)
else:
path = parsed_url.path
if proto == "unix" and parsed_url.hostname is not None:
# For legacy reasons, we consider unix://path
# to be valid and equivalent to unix:///path
path = "/".join((parsed_url.hostname, path))
path = parsed_url.path
if proto == "unix" and parsed_url.hostname is not None:
# For legacy reasons, we consider unix://path
# to be valid and equivalent to unix:///path
path = "/".join((parsed_url.hostname, path))
netloc = parsed_url.netloc
if proto in ("tcp", "ssh"):
@@ -419,7 +417,7 @@ def parse_bytes(s):
else:
digits_part = s[:-1]
if suffix in units.keys() or suffix.isdigit():
if suffix in units or suffix.isdigit():
try:
digits = float(digits_part)
except ValueError: