From 7c3b44124627d020e848e0b9cf706b8144827564 Mon Sep 17 00:00:00 2001 From: "patchback[bot]" <45432694+patchback[bot]@users.noreply.github.com> Date: Thu, 5 Sep 2024 22:01:56 +0200 Subject: [PATCH] [PR #8822/7e978c77 backport][stable-9] use dict comprehension in plugins, part 2 (#8832) use dict comprehension in plugins, part 2 (#8822) * use dict comprehension in plugins * add changelog frag (cherry picked from commit 7e978c77b4a1d3f317f65a544ec5f3051161fba0) Co-authored-by: Alexei Znamensky <103110+russoz@users.noreply.github.com> --- .../fragments/8822-dict-comprehension.yml | 21 +++++++++++++++++++ plugins/lookup/credstash.py | 6 +++--- .../identity/keycloak/keycloak.py | 3 +-- plugins/module_utils/mh/deco.py | 8 +++---- plugins/module_utils/redfish_utils.py | 18 +++++++++------- plugins/module_utils/scaleway.py | 11 ++++------ plugins/modules/etcd3.py | 9 ++------ plugins/modules/gitlab_project.py | 10 +++------ plugins/modules/hwc_ecs_instance.py | 3 +-- plugins/modules/hwc_evs_disk.py | 3 +-- plugins/modules/hwc_vpc_eip.py | 3 +-- plugins/modules/hwc_vpc_peering_connect.py | 3 +-- plugins/modules/hwc_vpc_port.py | 3 +-- plugins/modules/hwc_vpc_subnet.py | 6 ++---- plugins/modules/ipa_otptoken.py | 4 +--- plugins/modules/keycloak_user_federation.py | 7 +++++-- plugins/modules/lxc_container.py | 6 +++--- plugins/modules/proxmox_kvm.py | 4 ++-- plugins/modules/scaleway_security_group.py | 6 +++--- plugins/modules/ufw.py | 2 +- plugins/modules/vmadm.py | 8 ++++--- 21 files changed, 76 insertions(+), 68 deletions(-) create mode 100644 changelogs/fragments/8822-dict-comprehension.yml diff --git a/changelogs/fragments/8822-dict-comprehension.yml b/changelogs/fragments/8822-dict-comprehension.yml new file mode 100644 index 0000000000..cefb673bb8 --- /dev/null +++ b/changelogs/fragments/8822-dict-comprehension.yml @@ -0,0 +1,21 @@ +minor_changes: + - credstash lookup plugin - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - keycloak module utils - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - deco MH module utils - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - redfish_utils module utils - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - scaleway module utils - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - etcd3 - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - gitlab_project - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - hwc_ecs_instance - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - hwc_evs_disk - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - hwc_vpc_eip - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - hwc_vpc_peering_connect - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - hwc_vpc_port - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - hwc_vpc_subnet - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - ipa_otptoken - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - keycloak_user_federation - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - lxc_container - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - proxmox_kvm - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - scaleway_security_group - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - ufw - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). + - vmadm - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822). diff --git a/plugins/lookup/credstash.py b/plugins/lookup/credstash.py index 6a3f58595b..fd284f55c8 100644 --- a/plugins/lookup/credstash.py +++ b/plugins/lookup/credstash.py @@ -120,10 +120,10 @@ class LookupModule(LookupBase): aws_secret_access_key = self.get_option('aws_secret_access_key') aws_session_token = self.get_option('aws_session_token') - context = dict( - (k, v) for k, v in kwargs.items() + context = { + k: v for k, v in kwargs.items() if k not in ('version', 'region', 'table', 'profile_name', 'aws_access_key_id', 'aws_secret_access_key', 'aws_session_token') - ) + } kwargs_pass = { 'profile_name': profile_name, diff --git a/plugins/module_utils/identity/keycloak/keycloak.py b/plugins/module_utils/identity/keycloak/keycloak.py index 020b185a30..128b0fee13 100644 --- a/plugins/module_utils/identity/keycloak/keycloak.py +++ b/plugins/module_utils/identity/keycloak/keycloak.py @@ -185,8 +185,7 @@ def get_token(module_params): 'password': auth_password, } # Remove empty items, for instance missing client_secret - payload = dict( - (k, v) for k, v in temp_payload.items() if v is not None) + payload = {k: v for k, v in temp_payload.items() if v is not None} try: r = json.loads(to_native(open_url(auth_url, method='POST', validate_certs=validate_certs, http_agent=http_agent, timeout=connection_timeout, diff --git a/plugins/module_utils/mh/deco.py b/plugins/module_utils/mh/deco.py index c7b63b7050..408891cb8e 100644 --- a/plugins/module_utils/mh/deco.py +++ b/plugins/module_utils/mh/deco.py @@ -45,11 +45,11 @@ def module_fails_on_exception(func): @wraps(func) def wrapper(self, *args, **kwargs): + def fix_key(k): + return k if k not in conflict_list else "_" + k + def fix_var_conflicts(output): - result = dict([ - (k if k not in conflict_list else "_" + k, v) - for k, v in output.items() - ]) + result = {fix_key(k): v for k, v in output.items()} return result try: diff --git a/plugins/module_utils/redfish_utils.py b/plugins/module_utils/redfish_utils.py index edfc612466..c79506075a 100644 --- a/plugins/module_utils/redfish_utils.py +++ b/plugins/module_utils/redfish_utils.py @@ -613,9 +613,11 @@ class RedfishUtils(object): ai = dict((p['Name'], p) for p in params if 'Name' in p) if not ai: - ai = dict((k[:-24], - {'AllowableValues': v}) for k, v in action.items() - if k.endswith('@Redfish.AllowableValues')) + ai = { + k[:-24]: {'AllowableValues': v} + for k, v in action.items() + if k.endswith('@Redfish.AllowableValues') + } return ai def _get_allowable_values(self, action, name, default_values=None): @@ -2242,7 +2244,7 @@ class RedfishUtils(object): continue # If already set to requested value, remove it from PATCH payload - if data[u'Attributes'][attr_name] == attributes[attr_name]: + if data[u'Attributes'][attr_name] == attr_value: del attrs_to_patch[attr_name] warning = "" @@ -2780,9 +2782,11 @@ class RedfishUtils(object): def virtual_media_insert_via_patch(self, options, param_map, uri, data, image_only=False): # get AllowableValues - ai = dict((k[:-24], - {'AllowableValues': v}) for k, v in data.items() - if k.endswith('@Redfish.AllowableValues')) + ai = { + k[:-24]: {'AllowableValues': v} + for k, v in data.items() + if k.endswith('@Redfish.AllowableValues') + } # construct payload payload = self._insert_virt_media_payload(options, param_map, data, ai) if 'Inserted' not in payload and not image_only: diff --git a/plugins/module_utils/scaleway.py b/plugins/module_utils/scaleway.py index 1310ba5602..2b21ec3793 100644 --- a/plugins/module_utils/scaleway.py +++ b/plugins/module_utils/scaleway.py @@ -51,11 +51,11 @@ def scaleway_waitable_resource_argument_spec(): def payload_from_object(scw_object): - return dict( - (k, v) + return { + k: v for k, v in scw_object.items() if k != 'id' and v is not None - ) + } class ScalewayException(Exception): @@ -117,10 +117,7 @@ class SecretVariables(object): @staticmethod def list_to_dict(source_list, hashed=False): key_value = 'hashed_value' if hashed else 'value' - return dict( - (var['key'], var[key_value]) - for var in source_list - ) + return {var['key']: var[key_value] for var in source_list} @classmethod def decode(cls, secrets_list, values_list): diff --git a/plugins/modules/etcd3.py b/plugins/modules/etcd3.py index 2fdc3f2f83..b1bb181cf4 100644 --- a/plugins/modules/etcd3.py +++ b/plugins/modules/etcd3.py @@ -193,13 +193,8 @@ def run_module(): allowed_keys = ['host', 'port', 'ca_cert', 'cert_cert', 'cert_key', 'timeout', 'user', 'password'] - # TODO(evrardjp): Move this back to a dict comprehension when python 2.7 is - # the minimum supported version - # client_params = {key: value for key, value in module.params.items() if key in allowed_keys} - client_params = dict() - for key, value in module.params.items(): - if key in allowed_keys: - client_params[key] = value + + client_params = {key: value for key, value in module.params.items() if key in allowed_keys} try: etcd = etcd3.client(**client_params) except Exception as exp: diff --git a/plugins/modules/gitlab_project.py b/plugins/modules/gitlab_project.py index c5d2278ba0..a85f2bd827 100644 --- a/plugins/modules/gitlab_project.py +++ b/plugins/modules/gitlab_project.py @@ -534,11 +534,7 @@ class GitLabProject(object): @param arguments Attributes of the project ''' def get_options_with_value(self, arguments): - ret_arguments = dict() - for arg_key, arg_value in arguments.items(): - if arguments[arg_key] is not None: - ret_arguments[arg_key] = arg_value - + ret_arguments = {k: v for k, v in arguments.items() if v is not None} return ret_arguments ''' @@ -549,8 +545,8 @@ class GitLabProject(object): changed = False for arg_key, arg_value in arguments.items(): - if arguments[arg_key] is not None: - if getattr(project, arg_key, None) != arguments[arg_key]: + if arg_value is not None: + if getattr(project, arg_key, None) != arg_value: if arg_key == 'container_expiration_policy': old_val = getattr(project, arg_key, {}) final_val = {key: value for key, value in arg_value.items() if value is not None} diff --git a/plugins/modules/hwc_ecs_instance.py b/plugins/modules/hwc_ecs_instance.py index 9ba95dc96d..cc6ef926dd 100644 --- a/plugins/modules/hwc_ecs_instance.py +++ b/plugins/modules/hwc_ecs_instance.py @@ -1163,8 +1163,7 @@ def send_delete_volume_request(module, params, client, info): path_parameters = { "volume_id": ["volume_id"], } - data = dict((key, navigate_value(info, path)) - for key, path in path_parameters.items()) + data = {key: navigate_value(info, path) for key, path in path_parameters.items()} url = build_path(module, "cloudservers/{id}/detachvolume/{volume_id}", data) diff --git a/plugins/modules/hwc_evs_disk.py b/plugins/modules/hwc_evs_disk.py index 7d445ddd21..5f0e40b196 100644 --- a/plugins/modules/hwc_evs_disk.py +++ b/plugins/modules/hwc_evs_disk.py @@ -771,8 +771,7 @@ def async_wait(config, result, client, timeout): path_parameters = { "job_id": ["job_id"], } - data = dict((key, navigate_value(result, path)) - for key, path in path_parameters.items()) + data = {key: navigate_value(result, path) for key, path in path_parameters.items()} url = build_path(module, "jobs/{job_id}", data) diff --git a/plugins/modules/hwc_vpc_eip.py b/plugins/modules/hwc_vpc_eip.py index 5c44319409..c3039ca2e5 100644 --- a/plugins/modules/hwc_vpc_eip.py +++ b/plugins/modules/hwc_vpc_eip.py @@ -547,8 +547,7 @@ def async_wait_create(config, result, client, timeout): path_parameters = { "publicip_id": ["publicip", "id"], } - data = dict((key, navigate_value(result, path)) - for key, path in path_parameters.items()) + data = {key: navigate_value(result, path) for key, path in path_parameters.items()} url = build_path(module, "publicips/{publicip_id}", data) diff --git a/plugins/modules/hwc_vpc_peering_connect.py b/plugins/modules/hwc_vpc_peering_connect.py index 2d6832ce5d..854d89e76a 100644 --- a/plugins/modules/hwc_vpc_peering_connect.py +++ b/plugins/modules/hwc_vpc_peering_connect.py @@ -407,8 +407,7 @@ def async_wait_create(config, result, client, timeout): path_parameters = { "peering_id": ["peering", "id"], } - data = dict((key, navigate_value(result, path)) - for key, path in path_parameters.items()) + data = {key: navigate_value(result, path) for key, path in path_parameters.items()} url = build_path(module, "v2.0/vpc/peerings/{peering_id}", data) diff --git a/plugins/modules/hwc_vpc_port.py b/plugins/modules/hwc_vpc_port.py index 2d830493d4..08b1c0607d 100644 --- a/plugins/modules/hwc_vpc_port.py +++ b/plugins/modules/hwc_vpc_port.py @@ -560,8 +560,7 @@ def async_wait_create(config, result, client, timeout): path_parameters = { "port_id": ["port", "id"], } - data = dict((key, navigate_value(result, path)) - for key, path in path_parameters.items()) + data = {key: navigate_value(result, path) for key, path in path_parameters.items()} url = build_path(module, "ports/{port_id}", data) diff --git a/plugins/modules/hwc_vpc_subnet.py b/plugins/modules/hwc_vpc_subnet.py index 7ba7473301..ff6e425ca9 100644 --- a/plugins/modules/hwc_vpc_subnet.py +++ b/plugins/modules/hwc_vpc_subnet.py @@ -440,8 +440,7 @@ def async_wait_create(config, result, client, timeout): path_parameters = { "subnet_id": ["subnet", "id"], } - data = dict((key, navigate_value(result, path)) - for key, path in path_parameters.items()) + data = {key: navigate_value(result, path) for key, path in path_parameters.items()} url = build_path(module, "subnets/{subnet_id}", data) @@ -538,8 +537,7 @@ def async_wait_update(config, result, client, timeout): path_parameters = { "subnet_id": ["subnet", "id"], } - data = dict((key, navigate_value(result, path)) - for key, path in path_parameters.items()) + data = {key: navigate_value(result, path) for key, path in path_parameters.items()} url = build_path(module, "subnets/{subnet_id}", data) diff --git a/plugins/modules/ipa_otptoken.py b/plugins/modules/ipa_otptoken.py index 567674f935..d8a5b3cf1d 100644 --- a/plugins/modules/ipa_otptoken.py +++ b/plugins/modules/ipa_otptoken.py @@ -392,9 +392,7 @@ def ensure(module, client): 'counter': 'ipatokenhotpcounter'} # Create inverse dictionary for mapping return values - ipa_to_ansible = {} - for (k, v) in ansible_to_ipa.items(): - ipa_to_ansible[v] = k + ipa_to_ansible = {v: k for k, v in ansible_to_ipa.items()} unmodifiable_after_creation = ['otptype', 'secretkey', 'algorithm', 'digits', 'offset', 'interval', 'counter'] diff --git a/plugins/modules/keycloak_user_federation.py b/plugins/modules/keycloak_user_federation.py index 05f884cc1e..3f65af3a93 100644 --- a/plugins/modules/keycloak_user_federation.py +++ b/plugins/modules/keycloak_user_federation.py @@ -847,8 +847,11 @@ def main(): # Keycloak API expects config parameters to be arrays containing a single string element if config is not None: - module.params['config'] = dict((k, [str(v).lower() if not isinstance(v, str) else v]) - for k, v in config.items() if config[k] is not None) + module.params['config'] = { + k: [str(v).lower() if not isinstance(v, str) else v] + for k, v in config.items() + if config[k] is not None + } if mappers is not None: for mapper in mappers: diff --git a/plugins/modules/lxc_container.py b/plugins/modules/lxc_container.py index 7ded041e93..2d768eaafd 100644 --- a/plugins/modules/lxc_container.py +++ b/plugins/modules/lxc_container.py @@ -683,11 +683,11 @@ class LxcContainerManagement(object): variables.pop(v, None) false_values = BOOLEANS_FALSE.union([None, '']) - result = dict( - (v, self.module.params[k]) + result = { + v: self.module.params[k] for k, v in variables.items() if self.module.params[k] not in false_values - ) + } return result def _config(self): diff --git a/plugins/modules/proxmox_kvm.py b/plugins/modules/proxmox_kvm.py index e2b708170e..771ddd902f 100644 --- a/plugins/modules/proxmox_kvm.py +++ b/plugins/modules/proxmox_kvm.py @@ -1032,7 +1032,7 @@ class ProxmoxKvmAnsible(ProxmoxAnsible): # Sanitize kwargs. Remove not defined args and ensure True and False converted to int. kwargs = {k: v for k, v in kwargs.items() if v is not None} - kwargs.update(dict([k, int(v)] for k, v in kwargs.items() if isinstance(v, bool))) + kwargs.update({k: int(v) for k, v in kwargs.items() if isinstance(v, bool)}) version = self.version() pve_major_version = 3 if version < LooseVersion('4.0') else version.version[0] @@ -1163,7 +1163,7 @@ class ProxmoxKvmAnsible(ProxmoxAnsible): for param in valid_clone_params: if self.module.params[param] is not None: clone_params[param] = self.module.params[param] - clone_params.update(dict([k, int(v)] for k, v in clone_params.items() if isinstance(v, bool))) + clone_params.update({k: int(v) for k, v in clone_params.items() if isinstance(v, bool)}) taskid = proxmox_node.qemu(vmid).clone.post(newid=newid, name=name, **clone_params) else: taskid = proxmox_node.qemu.create(vmid=vmid, name=name, memory=memory, cpu=cpu, cores=cores, sockets=sockets, **kwargs) diff --git a/plugins/modules/scaleway_security_group.py b/plugins/modules/scaleway_security_group.py index c09bc34bad..0c7f3f6ec6 100644 --- a/plugins/modules/scaleway_security_group.py +++ b/plugins/modules/scaleway_security_group.py @@ -135,11 +135,11 @@ from uuid import uuid4 def payload_from_security_group(security_group): - return dict( - (k, v) + return { + k: v for k, v in security_group.items() if k != 'id' and v is not None - ) + } def present_strategy(api, security_group): diff --git a/plugins/modules/ufw.py b/plugins/modules/ufw.py index 5d187793bd..7a90647979 100644 --- a/plugins/modules/ufw.py +++ b/plugins/modules/ufw.py @@ -446,7 +446,7 @@ def main(): params = module.params - commands = dict((key, params[key]) for key in command_keys if params[key]) + commands = {key: params[key] for key in command_keys if params[key]} # Ensure ufw is available ufw_bin = module.get_bin_path('ufw', True) diff --git a/plugins/modules/vmadm.py b/plugins/modules/vmadm.py index bfe6148375..923a902bcf 100644 --- a/plugins/modules/vmadm.py +++ b/plugins/modules/vmadm.py @@ -558,9 +558,11 @@ def create_payload(module, uuid): # Filter out the few options that are not valid VM properties. module_options = ['force', 'state'] - # @TODO make this a simple {} comprehension as soon as py2 is ditched - # @TODO {k: v for k, v in p.items() if k not in module_options} - vmdef = dict([(k, v) for k, v in module.params.items() if k not in module_options and v]) + vmdef = { + k: v + for k, v in module.params.items() + if k not in module_options and v + } try: vmdef_json = json.dumps(vmdef)