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
+96 -88
View File
@@ -37,21 +37,21 @@ _DEFAULT_IP_REPLACEMENT_STRING = (
)
_MOUNT_OPTION_TYPES = dict(
create_mountpoint=("bind",),
labels=("volume",),
no_copy=("volume",),
non_recursive=("bind",),
propagation=("bind",),
read_only_force_recursive=("bind",),
read_only_non_recursive=("bind",),
subpath=("volume", "image"),
tmpfs_size=("tmpfs",),
tmpfs_mode=("tmpfs",),
tmpfs_options=("tmpfs",),
volume_driver=("volume",),
volume_options=("volume",),
)
_MOUNT_OPTION_TYPES = {
"create_mountpoint": ("bind",),
"labels": ("volume",),
"no_copy": ("volume",),
"non_recursive": ("bind",),
"propagation": ("bind",),
"read_only_force_recursive": ("bind",),
"read_only_non_recursive": ("bind",),
"subpath": ("volume", "image"),
"tmpfs_size": ("tmpfs",),
"tmpfs_mode": ("tmpfs",),
"tmpfs_options": ("tmpfs",),
"volume_driver": ("volume",),
"volume_options": ("volume",),
}
def _get_ansible_type(value_type):
@@ -629,7 +629,7 @@ def _preprocess_ulimits(module, values):
return values
result = []
for limit in values["ulimits"]:
limits = dict()
limits = {}
pieces = limit.split(":")
if len(pieces) >= 2:
limits["Name"] = pieces[0]
@@ -644,7 +644,7 @@ def _preprocess_ulimits(module, values):
def _preprocess_mounts(module, values):
last = dict()
last = {}
def check_collision(t, name):
if t in last:
@@ -970,53 +970,53 @@ OPTION_DEVICE_READ_BPS = OptionGroup().add_option(
"device_read_bps",
value_type="set",
elements="dict",
ansible_suboptions=dict(
path=dict(required=True, type="str"),
rate=dict(required=True, type="str"),
),
ansible_suboptions={
"path": {"type": "str", "required": True},
"rate": {"type": "str", "required": True},
},
)
OPTION_DEVICE_WRITE_BPS = OptionGroup().add_option(
"device_write_bps",
value_type="set",
elements="dict",
ansible_suboptions=dict(
path=dict(required=True, type="str"),
rate=dict(required=True, type="str"),
),
ansible_suboptions={
"path": {"type": "str", "required": True},
"rate": {"type": "str", "required": True},
},
)
OPTION_DEVICE_READ_IOPS = OptionGroup().add_option(
"device_read_iops",
value_type="set",
elements="dict",
ansible_suboptions=dict(
path=dict(required=True, type="str"),
rate=dict(required=True, type="int"),
),
ansible_suboptions={
"path": {"type": "str", "required": True},
"rate": {"type": "int", "required": True},
},
)
OPTION_DEVICE_WRITE_IOPS = OptionGroup().add_option(
"device_write_iops",
value_type="set",
elements="dict",
ansible_suboptions=dict(
path=dict(required=True, type="str"),
rate=dict(required=True, type="int"),
),
ansible_suboptions={
"path": {"type": "str", "required": True},
"rate": {"type": "int", "required": True},
},
)
OPTION_DEVICE_REQUESTS = OptionGroup().add_option(
"device_requests",
value_type="set",
elements="dict",
ansible_suboptions=dict(
capabilities=dict(type="list", elements="list"),
count=dict(type="int"),
device_ids=dict(type="list", elements="str"),
driver=dict(type="str"),
options=dict(type="dict"),
),
ansible_suboptions={
"capabilities": {"type": "list", "elements": "list"},
"count": {"type": "int"},
"device_ids": {"type": "list", "elements": "str"},
"driver": {"type": "str"},
"options": {"type": "dict"},
},
)
OPTION_DEVICE_CGROUP_RULES = OptionGroup().add_option(
@@ -1066,15 +1066,15 @@ OPTION_GROUPS = OptionGroup().add_option("groups", value_type="set", elements="s
OPTION_HEALTHCHECK = OptionGroup(preprocess=_preprocess_healthcheck).add_option(
"healthcheck",
value_type="dict",
ansible_suboptions=dict(
test=dict(type="raw"),
test_cli_compatible=dict(type="bool", default=False),
interval=dict(type="str"),
timeout=dict(type="str"),
start_period=dict(type="str"),
start_interval=dict(type="str"),
retries=dict(type="int"),
),
ansible_suboptions={
"test": {"type": "raw"},
"test_cli_compatible": {"type": "bool", "default": False},
"interval": {"type": "str"},
"timeout": {"type": "str"},
"start_period": {"type": "str"},
"start_interval": {"type": "str"},
"retries": {"type": "int"},
},
)
OPTION_HOSTNAME = OptionGroup().add_option("hostname", value_type="str")
@@ -1143,16 +1143,16 @@ OPTION_NETWORK = (
"networks",
value_type="set",
elements="dict",
ansible_suboptions=dict(
name=dict(type="str", required=True),
ipv4_address=dict(type="str"),
ipv6_address=dict(type="str"),
aliases=dict(type="list", elements="str"),
links=dict(type="list", elements="str"),
mac_address=dict(type="str"),
driver_opts=dict(type="dict"),
gw_priority=dict(type="int"),
),
ansible_suboptions={
"name": {"type": "str", "required": True},
"ipv4_address": {"type": "str"},
"ipv6_address": {"type": "str"},
"aliases": {"type": "list", "elements": "str"},
"links": {"type": "list", "elements": "str"},
"mac_address": {"type": "str"},
"driver_opts": {"type": "dict"},
"gw_priority": {"type": "int"},
},
)
)
@@ -1232,35 +1232,43 @@ OPTION_MOUNTS_VOLUMES = (
"mounts",
value_type="set",
elements="dict",
ansible_suboptions=dict(
target=dict(type="str", required=True),
source=dict(type="str"),
type=dict(
type="str",
choices=["bind", "volume", "tmpfs", "npipe", "cluster", "image"],
default="volume",
),
read_only=dict(type="bool"),
consistency=dict(
type="str", choices=["default", "consistent", "cached", "delegated"]
),
propagation=dict(
type="str",
choices=["private", "rprivate", "shared", "rshared", "slave", "rslave"],
),
no_copy=dict(type="bool"),
labels=dict(type="dict"),
volume_driver=dict(type="str"),
volume_options=dict(type="dict"),
tmpfs_size=dict(type="str"),
tmpfs_mode=dict(type="str"),
non_recursive=dict(type="bool"),
create_mountpoint=dict(type="bool"),
read_only_non_recursive=dict(type="bool"),
read_only_force_recursive=dict(type="bool"),
subpath=dict(type="str"),
tmpfs_options=dict(type="list", elements="dict"),
),
ansible_suboptions={
"target": {"type": "str", "required": True},
"source": {"type": "str"},
"type": {
"type": "str",
"choices": ["bind", "volume", "tmpfs", "npipe", "cluster", "image"],
"default": "volume",
},
"read_only": {"type": "bool"},
"consistency": {
"type": "str",
"choices": ["default", "consistent", "cached", "delegated"],
},
"propagation": {
"type": "str",
"choices": [
"private",
"rprivate",
"shared",
"rshared",
"slave",
"rslave",
],
},
"no_copy": {"type": "bool"},
"labels": {"type": "dict"},
"volume_driver": {"type": "str"},
"volume_options": {"type": "dict"},
"tmpfs_size": {"type": "str"},
"tmpfs_mode": {"type": "str"},
"non_recursive": {"type": "bool"},
"create_mountpoint": {"type": "bool"},
"read_only_non_recursive": {"type": "bool"},
"read_only_force_recursive": {"type": "bool"},
"subpath": {"type": "str"},
"tmpfs_options": {"type": "list", "elements": "dict"},
},
)
.add_option("volumes", value_type="set", elements="str")
.add_option(
@@ -398,13 +398,15 @@ class DockerAPIEngineDriver(EngineDriver):
# New docker daemon versions do not allow containers to be removed
# if they are paused. Make sure we do not end up in an infinite loop.
if count == 3:
raise RuntimeError(f"{exc} [tried to unpause three times]")
raise RuntimeError(
f"{exc} [tried to unpause three times]"
) from exc
count += 1
# Unpause
try:
self.unpause_container(client, container_id)
except Exception as exc2:
raise RuntimeError(f"{exc2} [while unpausing]")
raise RuntimeError(f"{exc2} [while unpausing]") from exc2
# Now try again
continue
raise
@@ -429,13 +431,15 @@ class DockerAPIEngineDriver(EngineDriver):
# New docker daemon versions do not allow containers to be removed
# if they are paused. Make sure we do not end up in an infinite loop.
if count == 3:
raise RuntimeError(f"{exc} [tried to unpause three times]")
raise RuntimeError(
f"{exc} [tried to unpause three times]"
) from exc
count += 1
# Unpause
try:
self.unpause_container(client, container_id)
except Exception as exc2:
raise RuntimeError(f"{exc2} [while unpausing]")
raise RuntimeError(f"{exc2} [while unpausing]") from exc2
# Now try again
continue
if (
@@ -817,28 +821,28 @@ def _preprocess_devices(module, client, api_version, value):
parts = device.split(":")
if len(parts) == 1:
expected_devices.append(
dict(
CgroupPermissions="rwm",
PathInContainer=parts[0],
PathOnHost=parts[0],
)
{
"CgroupPermissions": "rwm",
"PathInContainer": parts[0],
"PathOnHost": parts[0],
}
)
elif len(parts) == 2:
parts = device.split(":")
expected_devices.append(
dict(
CgroupPermissions="rwm",
PathInContainer=parts[1],
PathOnHost=parts[0],
)
{
"CgroupPermissions": "rwm",
"PathInContainer": parts[1],
"PathOnHost": parts[0],
}
)
else:
expected_devices.append(
dict(
CgroupPermissions=parts[2],
PathInContainer=parts[1],
PathOnHost=parts[0],
)
{
"CgroupPermissions": parts[2],
"PathInContainer": parts[1],
"PathOnHost": parts[0],
}
)
return expected_devices
@@ -1186,7 +1190,7 @@ def _get_expected_values_mounts(
expected_values["mounts"] = values["mounts"]
# volumes
expected_vols = dict()
expected_vols = {}
if image and image["Config"].get("Volumes"):
expected_vols.update(image["Config"].get("Volumes"))
if "volumes" in values:
@@ -1400,9 +1404,7 @@ def _get_values_ports(module, container, api_version, options, image, host_info)
# "ExposedPorts": null returns None type & causes AttributeError - PR #5517
if config.get("ExposedPorts") is not None:
expected_exposed = [
_normalize_port(p) for p in config.get("ExposedPorts", dict()).keys()
]
expected_exposed = [_normalize_port(p) for p in config.get("ExposedPorts", {})]
else:
expected_exposed = []
+113 -104
View File
@@ -42,7 +42,7 @@ class Container(DockerBaseClass):
@property
def exists(self):
return True if self.container else False
return bool(self.container)
@property
def removing(self):
@@ -232,17 +232,17 @@ class ContainerManager(DockerBaseClass):
"name"
]
if self.param_container_default_behavior == "compatibility":
old_default_values = dict(
auto_remove=False,
detach=True,
init=False,
interactive=False,
memory="0",
paused=False,
privileged=False,
read_only=False,
tty=False,
)
old_default_values = {
"auto_remove": False,
"detach": True,
"init": False,
"interactive": False,
"memory": "0",
"paused": False,
"privileged": False,
"read_only": False,
"tty": False,
}
for param, value in old_default_values.items():
if self.module.params[param] is None:
self.module.params[param] = value
@@ -487,7 +487,7 @@ class ContainerManager(DockerBaseClass):
)
container = self._get_container(container.id)
self.results["changed"] = True
self.results["actions"].append(dict(set_paused=self.param_paused))
self.results["actions"].append({"set_paused": self.param_paused})
self.facts = container.raw
@@ -577,19 +577,19 @@ class ContainerManager(DockerBaseClass):
if already_to_latest:
self.results["changed"] = False
self.results["actions"].append(
dict(pulled_image=f"{repository}:{tag}", changed=False)
{"pulled_image": f"{repository}:{tag}", "changed": False}
)
else:
self.results["changed"] = True
self.results["actions"].append(
dict(pulled_image=f"{repository}:{tag}", changed=True)
{"pulled_image": f"{repository}:{tag}", "changed": True}
)
elif not image or self.param_pull_check_mode_behavior == "always":
# If the image is not there, or pull_check_mode_behavior == 'always', claim we'll
# pull. (Implicitly: if the image is there, claim it already was latest unless
# pull_check_mode_behavior == 'always'.)
self.results["changed"] = True
action = dict(pulled_image=f"{repository}:{tag}")
action = {"pulled_image": f"{repository}:{tag}"}
if not image:
action["changed"] = True
self.results["actions"].append(action)
@@ -817,7 +817,7 @@ class ContainerManager(DockerBaseClass):
network_info = connected_networks.get(network["name"])
if network_info is None:
different = True
differences.append(dict(parameter=network, container=None))
differences.append({"parameter": network, "container": None})
else:
diff = False
network_info_ipam = network_info.get("IPAMConfig") or {}
@@ -855,17 +855,17 @@ class ContainerManager(DockerBaseClass):
if diff:
different = True
differences.append(
dict(
parameter=network,
container=dict(
name=network["name"],
ipv4_address=network_info_ipam.get("IPv4Address"),
ipv6_address=network_info_ipam.get("IPv6Address"),
aliases=network_info.get("Aliases"),
links=network_info.get("Links"),
mac_address=network_info.get("MacAddress"),
),
)
{
"parameter": network,
"container": {
"name": network["name"],
"ipv4_address": network_info_ipam.get("IPv4Address"),
"ipv6_address": network_info_ipam.get("IPv6Address"),
"aliases": network_info.get("Aliases"),
"links": network_info.get("Links"),
"mac_address": network_info.get("MacAddress"),
},
}
)
return different, differences
@@ -892,7 +892,7 @@ class ContainerManager(DockerBaseClass):
if not keep:
extra = True
extra_networks.append(
dict(name=network, id=network_config["NetworkID"])
{"name": network, "id": network_config["NetworkID"]}
)
return extra, extra_networks
@@ -905,11 +905,11 @@ class ContainerManager(DockerBaseClass):
if has_network_differences:
if self.diff.get("differences"):
self.diff["differences"].append(
dict(network_differences=network_differences)
{"network_differences": network_differences}
)
else:
self.diff["differences"] = [
dict(network_differences=network_differences)
{"network_differences": network_differences}
]
for netdiff in network_differences:
self.diff_tracker.add(
@@ -928,9 +928,9 @@ class ContainerManager(DockerBaseClass):
has_extra_networks, extra_networks = self.has_extra_networks(container)
if has_extra_networks:
if self.diff.get("differences"):
self.diff["differences"].append(dict(purge_networks=extra_networks))
self.diff["differences"].append({"purge_networks": extra_networks})
else:
self.diff["differences"] = [dict(purge_networks=extra_networks)]
self.diff["differences"] = [{"purge_networks": extra_networks}]
for extra_network in extra_networks:
self.diff_tracker.add(
f"network.{extra_network['name']}", active=extra_network
@@ -944,7 +944,7 @@ class ContainerManager(DockerBaseClass):
# remove the container from the network, if connected
if diff.get("container"):
self.results["actions"].append(
dict(removed_from_network=diff["parameter"]["name"])
{"removed_from_network": diff["parameter"]["name"]}
)
if not self.check_mode:
try:
@@ -957,10 +957,10 @@ class ContainerManager(DockerBaseClass):
)
# connect to the network
self.results["actions"].append(
dict(
added_to_network=diff["parameter"]["name"],
network_parameters=diff["parameter"],
)
{
"added_to_network": diff["parameter"]["name"],
"network_parameters": diff["parameter"],
}
)
if not self.check_mode:
params = {
@@ -984,7 +984,7 @@ class ContainerManager(DockerBaseClass):
def _purge_networks(self, container, networks):
for network in networks:
self.results["actions"].append(dict(removed_from_network=network["name"]))
self.results["actions"].append({"removed_from_network": network["name"]})
if not self.check_mode:
try:
self.engine_driver.disconnect_container_from_network(
@@ -1015,11 +1015,11 @@ class ContainerManager(DockerBaseClass):
if key not in ("name", "id")
}
self.results["actions"].append(
dict(
created="Created container",
create_parameters=create_parameters,
networks=networks,
)
{
"created": "Created container",
"create_parameters": create_parameters,
"networks": networks,
}
)
self.results["changed"] = True
new_container = None
@@ -1035,7 +1035,7 @@ class ContainerManager(DockerBaseClass):
def container_start(self, container_id):
self.log(f"start container {container_id}")
self.results["actions"].append(dict(started=container_id))
self.results["actions"].append({"started": container_id})
self.results["changed"] = True
if not self.check_mode:
try:
@@ -1069,7 +1069,7 @@ class ContainerManager(DockerBaseClass):
if insp.raw:
insp.raw["Output"] = output
else:
insp.raw = dict(Output=output)
insp.raw = {"Output": output}
if status != 0:
# Set `failed` to True and return output as msg
self.results["failed"] = True
@@ -1083,9 +1083,12 @@ class ContainerManager(DockerBaseClass):
f"remove container container:{container_id} v:{volume_state} link:{link} force{force}"
)
self.results["actions"].append(
dict(
removed=container_id, volume_state=volume_state, link=link, force=force
)
{
"removed": container_id,
"volume_state": volume_state,
"link": link,
"force": force,
}
)
self.results["changed"] = True
if not self.check_mode:
@@ -1105,7 +1108,7 @@ class ContainerManager(DockerBaseClass):
self.log(f"update container {container_id}")
self.log(update_parameters, pretty_print=True)
self.results["actions"].append(
dict(updated=container_id, update_parameters=update_parameters)
{"updated": container_id, "update_parameters": update_parameters}
)
self.results["changed"] = True
if not self.check_mode:
@@ -1119,7 +1122,7 @@ class ContainerManager(DockerBaseClass):
def container_kill(self, container_id):
self.results["actions"].append(
dict(killed=container_id, signal=self.param_kill_signal)
{"killed": container_id, "signal": self.param_kill_signal}
)
self.results["changed"] = True
if not self.check_mode:
@@ -1132,7 +1135,7 @@ class ContainerManager(DockerBaseClass):
def container_restart(self, container_id):
self.results["actions"].append(
dict(restarted=container_id, timeout=self.module.params["stop_timeout"])
{"restarted": container_id, "timeout": self.module.params["stop_timeout"]}
)
self.results["changed"] = True
if not self.check_mode:
@@ -1149,7 +1152,7 @@ class ContainerManager(DockerBaseClass):
self.container_kill(container_id)
return
self.results["actions"].append(
dict(stopped=container_id, timeout=self.module.params["stop_timeout"])
{"stopped": container_id, "timeout": self.module.params["stop_timeout"]}
)
self.results["changed"] = True
if not self.check_mode:
@@ -1163,57 +1166,63 @@ class ContainerManager(DockerBaseClass):
def run_module(engine_driver):
module, active_options, client = engine_driver.setup(
argument_spec=dict(
cleanup=dict(type="bool", default=False),
comparisons=dict(type="dict"),
container_default_behavior=dict(
type="str",
default="no_defaults",
choices=["compatibility", "no_defaults"],
),
command_handling=dict(
type="str", choices=["compatibility", "correct"], default="correct"
),
default_host_ip=dict(type="str"),
force_kill=dict(type="bool", default=False, aliases=["forcekill"]),
image=dict(type="str"),
image_comparison=dict(
type="str",
choices=["desired-image", "current-image"],
default="desired-image",
),
image_label_mismatch=dict(
type="str", choices=["ignore", "fail"], default="ignore"
),
image_name_mismatch=dict(
type="str", choices=["ignore", "recreate"], default="recreate"
),
keep_volumes=dict(type="bool", default=True),
kill_signal=dict(type="str"),
name=dict(type="str", required=True),
networks_cli_compatible=dict(type="bool", default=True),
output_logs=dict(type="bool", default=False),
paused=dict(type="bool"),
pull=dict(
type="raw",
choices=["never", "missing", "always", True, False],
default="missing",
),
pull_check_mode_behavior=dict(
type="str",
choices=["image_not_present", "always"],
default="image_not_present",
),
recreate=dict(type="bool", default=False),
removal_wait_timeout=dict(type="float"),
restart=dict(type="bool", default=False),
state=dict(
type="str",
default="started",
choices=["absent", "present", "healthy", "started", "stopped"],
),
healthy_wait_timeout=dict(type="float", default=300),
),
argument_spec={
"cleanup": {"type": "bool", "default": False},
"comparisons": {"type": "dict"},
"container_default_behavior": {
"type": "str",
"default": "no_defaults",
"choices": ["compatibility", "no_defaults"],
},
"command_handling": {
"type": "str",
"choices": ["compatibility", "correct"],
"default": "correct",
},
"default_host_ip": {"type": "str"},
"force_kill": {"type": "bool", "default": False, "aliases": ["forcekill"]},
"image": {"type": "str"},
"image_comparison": {
"type": "str",
"choices": ["desired-image", "current-image"],
"default": "desired-image",
},
"image_label_mismatch": {
"type": "str",
"choices": ["ignore", "fail"],
"default": "ignore",
},
"image_name_mismatch": {
"type": "str",
"choices": ["ignore", "recreate"],
"default": "recreate",
},
"keep_volumes": {"type": "bool", "default": True},
"kill_signal": {"type": "str"},
"name": {"type": "str", "required": True},
"networks_cli_compatible": {"type": "bool", "default": True},
"output_logs": {"type": "bool", "default": False},
"paused": {"type": "bool"},
"pull": {
"type": "raw",
"choices": ["never", "missing", "always", True, False],
"default": "missing",
},
"pull_check_mode_behavior": {
"type": "str",
"choices": ["image_not_present", "always"],
"default": "image_not_present",
},
"recreate": {"type": "bool", "default": False},
"removal_wait_timeout": {"type": "float"},
"restart": {"type": "bool", "default": False},
"state": {
"type": "str",
"default": "started",
"choices": ["absent", "present", "healthy", "started", "stopped"],
},
"healthy_wait_timeout": {"type": "float", "default": 300},
},
required_if=[
("state", "present", ["image"]),
],