diff --git a/pylintrc b/pylintrc index 8f9c71bb937..d3fb7599fce 100644 --- a/pylintrc +++ b/pylintrc @@ -47,7 +47,12 @@ disable= redundant-u-string-prefix, raising-bad-type, unused-private-member, - used-before-assignment + used-before-assignment, + # These rules were added in Pylint >= 2.12, disable them to avoid making retroactive change + missing-timeout, + superfluous-parens, + implicit-str-concat, + unnecessary-dunder-call, [FORMAT] max-line-length=120 @@ -61,24 +66,8 @@ init-import=yes max-locals=25 # Maximum number of branch for function / method body max-branches=20 +# Temporally disable this check as inline disable is not working, see https://github.com/pylint-dev/pylint/issues/8806 +max-statements=500 [SIMILARITIES] min-similarity-lines=10 - -[BASIC] -# Naming hints based on PEP 8 (https://www.python.org/dev/peps/pep-0008/#naming-conventions). -# Consider these guidelines and not hard rules. Read PEP 8 for more details. - -# The invalid-name checker must be **enabled** for these hints to be used. -include-naming-hint=yes - -module-name-hint=lowercase (keep short; underscores are discouraged) -const-name-hint=UPPER_CASE_WITH_UNDERSCORES -class-name-hint=CapitalizedWords -class-attribute-name-hint=lower_case_with_underscores -attr-name-hint=lower_case_with_underscores -method-name-hint=lower_case_with_underscores -function-name-hint=lower_case_with_underscores -argument-name-hint=lower_case_with_underscores -variable-name-hint=lower_case_with_underscores -inlinevar-name-hint=lower_case_with_underscores (short is OK) diff --git a/src/azure-cli-core/azure/cli/core/aaz/_help.py b/src/azure-cli-core/azure/cli/core/aaz/_help.py index 0eb3bbb68ed..39aa80aedde 100644 --- a/src/azure-cli-core/azure/cli/core/aaz/_help.py +++ b/src/azure-cli-core/azure/cli/core/aaz/_help.py @@ -44,7 +44,7 @@ def show(self): key = self.keys[idx] if isinstance(schema, AAZObjectArg): try: - schema = schema[key] + schema = schema[key] # pylint: disable=unsubscriptable-object except AAZUndefinedValueError: # show the help of current schema break diff --git a/src/azure-cli-core/azure/cli/core/commands/__init__.py b/src/azure-cli-core/azure/cli/core/commands/__init__.py index 57d3cd475cb..f32b8d03074 100644 --- a/src/azure-cli-core/azure/cli/core/commands/__init__.py +++ b/src/azure-cli-core/azure/cli/core/commands/__init__.py @@ -724,7 +724,7 @@ def _run_jobs_serially(self, jobs, ids): expanded_arg, cmd_copy = job try: results.append(self._run_job(expanded_arg, cmd_copy)) - except(Exception, SystemExit) as ex: # pylint: disable=broad-except + except (Exception, SystemExit) as ex: # pylint: disable=broad-except exceptions.append((ex, id_arg)) return results, exceptions diff --git a/src/azure-cli-core/azure/cli/core/extension/__init__.py b/src/azure-cli-core/azure/cli/core/extension/__init__.py index ae05cc55319..302bf81a4ca 100644 --- a/src/azure-cli-core/azure/cli/core/extension/__init__.py +++ b/src/azure-cli-core/azure/cli/core/extension/__init__.py @@ -8,7 +8,7 @@ import traceback import json import re -from distutils.sysconfig import get_python_lib +from distutils.sysconfig import get_python_lib # pylint: disable=deprecated-module import pkginfo from knack.config import CLIConfig diff --git a/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py b/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py index 4d16ea9e884..6a79064c080 100644 --- a/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py +++ b/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py @@ -644,7 +644,7 @@ def request_data_from_registry(http_method, raise RegistryException( parse_error_message('Failed to request data due to a conflict.', response), response.status_code) - raise Exception(parse_error_message('Could not {} the requested data.'.format(http_method), response)) + raise Exception(parse_error_message('Could not {} the requested data.'.format(http_method), response)) # pylint: disable=broad-exception-raised except CLIError: raise except Exception as e: # pylint: disable=broad-except diff --git a/src/azure-cli/azure/cli/command_modules/acs/_format.py b/src/azure-cli/azure/cli/command_modules/acs/_format.py index 2d3a16b36d2..551ea140c0c 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/_format.py +++ b/src/azure-cli/azure/cli/command_modules/acs/_format.py @@ -174,7 +174,7 @@ def _func_set_preview_array(self, versions): for i, _ in enumerate(versions): versions[i] = self._func_set_preview(versions[i]) return versions - except(TypeError, ValueError): + except (TypeError, ValueError): return versions @functions.signature({'types': ['string']}) @@ -184,7 +184,7 @@ def _func_set_preview(self, version): # pylint: disable=no-self-use if preview_versions.get(version, False): return version + '(preview)' return version - except(TypeError, ValueError): + except (TypeError, ValueError): return version return CustomFunctions() diff --git a/src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py b/src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py index 755c6f78df2..94757d7cf36 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py +++ b/src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py @@ -3,7 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from distutils.version import StrictVersion +from distutils.version import StrictVersion # pylint: disable=deprecated-module from types import SimpleNamespace from knack.log import get_logger diff --git a/src/azure-cli/azure/cli/command_modules/acs/_roleassignments.py b/src/azure-cli/azure/cli/command_modules/acs/_roleassignments.py index f6c56881ed4..16988e730fd 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/_roleassignments.py +++ b/src/azure-cli/azure/cli/command_modules/acs/_roleassignments.py @@ -309,11 +309,11 @@ def ensure_aks_acr_role_assignment(cmd, assignee, registry_id, detach=False, is_ if not delete_role_assignments( cmd.cli_ctx, "acrpull", assignee, scope=registry_id, is_service_principal=is_service_principal ): - raise AzCLIError("Could not delete role assignments for ACR. " "Are you an Owner on this subscription?") + raise AzCLIError("Could not delete role assignments for ACR. Are you an Owner on this subscription?") return if not add_role_assignment(cmd, "acrpull", assignee, scope=registry_id, is_service_principal=is_service_principal): - raise AzCLIError("Could not create a role assignment for ACR. " "Are you an Owner on this subscription?") + raise AzCLIError("Could not create a role assignment for ACR. Are you an Owner on this subscription?") return diff --git a/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py b/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py index 34571da2334..bbae2975b7c 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py +++ b/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py @@ -122,7 +122,7 @@ def items(self): return self.__store.items() def __format_count(self): - untouched_keys = [x for x in self.__store.keys() if x not in self.__count.keys()] + untouched_keys = [x for x in self.__store if x not in self.__count] for k in untouched_keys: self.__count[k] = 0 diff --git a/src/azure-cli/azure/cli/command_modules/acs/custom.py b/src/azure-cli/azure/cli/command_modules/acs/custom.py index 61706b0772d..200f0fc5ed2 100644 --- a/src/azure-cli/azure/cli/command_modules/acs/custom.py +++ b/src/azure-cli/azure/cli/command_modules/acs/custom.py @@ -22,7 +22,7 @@ import uuid import webbrowser import zipfile -from distutils.version import StrictVersion +from distutils.version import StrictVersion # pylint: disable=deprecated-module from urllib.error import URLError from urllib.request import urlopen diff --git a/src/azure-cli/azure/cli/command_modules/appconfig/_featuremodels.py b/src/azure-cli/azure/cli/command_modules/appconfig/_featuremodels.py index 217e2cadba5..443a852362b 100644 --- a/src/azure-cli/azure/cli/command_modules/appconfig/_featuremodels.py +++ b/src/azure-cli/azure/cli/command_modules/appconfig/_featuremodels.py @@ -214,7 +214,7 @@ def map_featureflag_to_keyvalue(featureflag): except Exception as exception: error_msg = "Exception while converting feature flag to key value: {0}\n{1}".format(featureflag.key, exception) - raise Exception(error_msg) + raise Exception(error_msg) # pylint: disable=broad-exception-raised return set_kv diff --git a/src/azure-cli/azure/cli/command_modules/appconfig/_kv_helpers.py b/src/azure-cli/azure/cli/command_modules/appconfig/_kv_helpers.py index c5dff3f4713..ad400e859b2 100644 --- a/src/azure-cli/azure/cli/command_modules/appconfig/_kv_helpers.py +++ b/src/azure-cli/azure/cli/command_modules/appconfig/_kv_helpers.py @@ -36,9 +36,9 @@ from ._utils import prep_label_filter_for_url_encoding, validate_feature_flag_name, validate_feature_flag_key from ._models import (KeyValue, convert_configurationsetting_to_keyvalue, convert_keyvalue_to_configurationsetting, QueryFields) -from._featuremodels import (map_keyvalue_to_featureflag, - map_featureflag_to_keyvalue, - FeatureFlagValue) +from ._featuremodels import (map_keyvalue_to_featureflag, + map_featureflag_to_keyvalue, + FeatureFlagValue) logger = get_logger(__name__) FEATURE_MANAGEMENT_KEYWORDS = ["FeatureManagement", "featureManagement", "feature_management", "feature-management"] @@ -680,7 +680,7 @@ def __print_features_preview(old_json, new_json, strict=False, yes=False): diff_output = __find_ff_diff(old_json=old_json, new_json=new_json, strict=strict) - if diff_output == {}: + if not diff_output: logger.warning('\nThe target configuration already contains all feature flags in source. No changes will be made.') return False @@ -699,7 +699,7 @@ def __print_kv_preview(old_json, new_json, strict=False, yes=False): diff_output = __find_kv_diff(old_json=old_json, new_json=new_json, strict=strict) - if diff_output == {}: + if not diff_output: logger.warning('\nTarget configuration already contains all key-values in source. No changes will be made.') return False diff --git a/src/azure-cli/azure/cli/command_modules/appservice/_create_util.py b/src/azure-cli/azure/cli/command_modules/appservice/_create_util.py index 15644ef2fdd..10adfdd6153 100644 --- a/src/azure-cli/azure/cli/command_modules/appservice/_create_util.py +++ b/src/azure-cli/azure/cli/command_modules/appservice/_create_util.py @@ -484,7 +484,7 @@ def _get_dotnet_main_project_csproj(dirPath): if len(ll) == 1: csproj_path = os.path.join(dirPath, ll[0]) else: - raise Exception('{} should contain only one .csproj file'.format(dirPath)) + raise Exception('{} should contain only one .csproj file'.format(dirPath)) # pylint: disable=broad-exception-raised return csproj_path diff --git a/src/azure-cli/azure/cli/command_modules/appservice/_validators.py b/src/azure-cli/azure/cli/command_modules/appservice/_validators.py index 3f044120a51..793559a7e2e 100644 --- a/src/azure-cli/azure/cli/command_modules/appservice/_validators.py +++ b/src/azure-cli/azure/cli/command_modules/appservice/_validators.py @@ -285,7 +285,7 @@ def _validate_ip_address_existence(cmd, namespace): scm_site = namespace.scm_site configs = _generic_site_operation(cmd.cli_ctx, resource_group_name, name, 'get_configuration', slot) access_rules = configs.scm_ip_security_restrictions if scm_site else configs.ip_security_restrictions - ip_exists = [(lambda x: x.ip_address == namespace.ip_address)(x) for x in access_rules] + ip_exists = [x.ip_address == namespace.ip_address for x in access_rules] if True in ip_exists: raise ArgumentUsageError('IP address: ' + namespace.ip_address + ' already exists. ' 'Cannot add duplicate IP address values.') @@ -521,11 +521,11 @@ def validate_registry_user(namespace): if namespace.environment and namespace.registry_username: if not namespace.registry_server or (not namespace.registry_password and ACR_IMAGE_SUFFIX not in namespace.registry_server): # pylint: disable=line-too-long raise RequiredArgumentMissingError("Usage error: --registry-server, --registry-password and" - " --registry-username are required together if not using Azure Container Registry") + " --registry-username are required together if not using Azure Container Registry") # pylint: disable=line-too-long def validate_registry_pass(namespace): if namespace.environment and namespace.registry_password: if not namespace.registry_server or (not namespace.registry_username and ACR_IMAGE_SUFFIX not in namespace.registry_server): # pylint: disable=line-too-long raise RequiredArgumentMissingError("Usage error: --registry-server, --registry-password and" - " --registry-username are required together if not using Azure Container Registry") + " --registry-username are required together if not using Azure Container Registry") # pylint: disable=line-too-long diff --git a/src/azure-cli/azure/cli/command_modules/appservice/custom.py b/src/azure-cli/azure/cli/command_modules/appservice/custom.py index be941c23257..847f8962565 100644 --- a/src/azure-cli/azure/cli/command_modules/appservice/custom.py +++ b/src/azure-cli/azure/cli/command_modules/appservice/custom.py @@ -5462,7 +5462,7 @@ def add_github_actions(cmd, resource_group, name, repo, runtime=None, token=None cmd=cmd, resource_group=resource_group, name=name, slot=slot, is_linux=is_linux) app_runtime_string = None - if(app_runtime_info and app_runtime_info['display_name']): + if (app_runtime_info and app_runtime_info['display_name']): app_runtime_string = app_runtime_info['display_name'] github_actions_version = None diff --git a/src/azure-cli/azure/cli/command_modules/appservice/static_sites.py b/src/azure-cli/azure/cli/command_modules/appservice/static_sites.py index c90e8703b04..b573bd85d08 100644 --- a/src/azure-cli/azure/cli/command_modules/appservice/static_sites.py +++ b/src/azure-cli/azure/cli/command_modules/appservice/static_sites.py @@ -520,7 +520,7 @@ def delete_staticsite(cmd, name, resource_group_name=None, no_wait=False): def _parse_pair(pair, delimiter): if delimiter not in pair: - InvalidArgumentValueError("invalid format of pair {0}".format(pair)) + raise InvalidArgumentValueError("invalid format of pair {0}".format(pair)) index = pair.index(delimiter) return pair[:index], pair[1 + index:] diff --git a/src/azure-cli/azure/cli/command_modules/aro/_validators.py b/src/azure-cli/azure/cli/command_modules/aro/_validators.py index da43583a5a4..95369827150 100644 --- a/src/azure-cli/azure/cli/command_modules/aro/_validators.py +++ b/src/azure-cli/azure/cli/command_modules/aro/_validators.py @@ -114,7 +114,7 @@ def validate_pull_secret(namespace): namespace.pull_secret = file.read().rstrip('\n') if not isinstance(json.loads(namespace.pull_secret), dict): - raise Exception() + raise Exception() # pylint: disable=broad-exception-raised except Exception as e: raise InvalidArgumentValueError("Invalid --pull-secret.") from e diff --git a/src/azure-cli/azure/cli/command_modules/backup/custom.py b/src/azure-cli/azure/cli/command_modules/backup/custom.py index d078eaab95c..810bffe337d 100644 --- a/src/azure-cli/azure/cli/command_modules/backup/custom.py +++ b/src/azure-cli/azure/cli/command_modules/backup/custom.py @@ -929,7 +929,7 @@ def move_recovery_points(cmd, resource_group_name, vault_name, item_name, rp_nam container_uri = cust_help.get_protection_container_uri_from_id(item_name.id) item_uri = cust_help.get_protected_item_uri_from_id(item_name.id) - if source_tier not in common.tier_type_map.keys(): + if source_tier not in common.tier_type_map: raise InvalidArgumentValueError('This source tier-type is not accepted by move command at present.') parameters = MoveRPAcrossTiersRequest(source_tier_type=common.tier_type_map[source_tier], @@ -988,9 +988,9 @@ def _get_trigger_restore_properties(rp_name, vault_location, storage_account_id, mi_user_assigned, restore_mode): if disk_encryption_set_id is not None: - if not(encryption.properties.encryption_at_rest_type == "CustomerManaged" and - recovery_point.properties.is_managed_virtual_machine and - not recovery_point.properties.is_source_vm_encrypted): + if not (encryption.properties.encryption_at_rest_type == "CustomerManaged" and + recovery_point.properties.is_managed_virtual_machine and + not recovery_point.properties.is_source_vm_encrypted): raise InvalidArgumentValueError("disk_encryption_set_id can't be specified") identity_info = None diff --git a/src/azure-cli/azure/cli/command_modules/backup/custom_wl.py b/src/azure-cli/azure/cli/command_modules/backup/custom_wl.py index f499bbc3aa6..f009e31bc9b 100644 --- a/src/azure-cli/azure/cli/command_modules/backup/custom_wl.py +++ b/src/azure-cli/azure/cli/command_modules/backup/custom_wl.py @@ -415,7 +415,7 @@ def move_wl_recovery_points(cmd, resource_group_name, vault_name, item_name, rp_ container_uri = cust_help.get_protection_container_uri_from_id(item_name.id) item_uri = cust_help.get_protected_item_uri_from_id(item_name.id) - if source_tier not in common.tier_type_map.keys(): + if source_tier not in common.tier_type_map: raise InvalidArgumentValueError('This source tier-type is not accepted by move command at present.') parameters = MoveRPAcrossTiersRequest(source_tier_type=common.tier_type_map[source_tier], diff --git a/src/azure-cli/azure/cli/command_modules/batch/_command_type.py b/src/azure-cli/azure/cli/command_modules/batch/_command_type.py index 0465fd27f76..083c9748a2b 100644 --- a/src/azure-cli/azure/cli/command_modules/batch/_command_type.py +++ b/src/azure-cli/azure/cli/command_modules/batch/_command_type.py @@ -294,9 +294,8 @@ def deserialize_json(self, kwargs, json_obj): except DeserializationError as error: message += f": {error}" raise ValueError(message.format(self._request_param['model'])) - else: - if kwargs[self._request_param['name']] is None: - raise ValueError(message.format(self._request_param['model'])) + if kwargs[self._request_param['name']] is None: + raise ValueError(message.format(self._request_param['model'])) def queue_argument(self, name=None, path=None, root=None, options=None, type=None, # pylint: disable=redefined-builtin diff --git a/src/azure-cli/azure/cli/command_modules/batch/_validators.py b/src/azure-cli/azure/cli/command_modules/batch/_validators.py index f9d2c35cfa8..e412ec29447 100644 --- a/src/azure-cli/azure/cli/command_modules/batch/_validators.py +++ b/src/azure-cli/azure/cli/command_modules/batch/_validators.py @@ -209,14 +209,13 @@ def validate_options(namespace): end = namespace.end_range except AttributeError: return - else: - namespace.ocp_range = None - del namespace.start_range - del namespace.end_range - if start or end: - start = start if start else 0 - end = end if end else "" - namespace.ocp_range = f"bytes={start}-{end}" + namespace.ocp_range = None + del namespace.start_range + del namespace.end_range + if start or end: + start = start if start else 0 + end = end if end else "" + namespace.ocp_range = f"bytes={start}-{end}" def validate_file_destination(namespace): @@ -225,22 +224,21 @@ def validate_file_destination(namespace): path = namespace.destination except AttributeError: return - else: - # TODO: Need to confirm this logic... - file_path = path - file_dir = os.path.dirname(path) - if os.path.isdir(path): - file_name = os.path.basename(namespace.file_name) - file_path = os.path.join(path, file_name) - elif not os.path.isdir(file_dir): - try: - os.mkdir(file_dir) - except EnvironmentError as exp: - message = "Directory {} does not exist, and cannot be created: {}" - raise ValueError(message.format(file_dir, exp)) - if os.path.isfile(file_path): - raise ValueError(f"File {file_path} already exists.") - namespace.destination = file_path + # TODO: Need to confirm this logic... + file_path = path + file_dir = os.path.dirname(path) + if os.path.isdir(path): + file_name = os.path.basename(namespace.file_name) + file_path = os.path.join(path, file_name) + elif not os.path.isdir(file_dir): + try: + os.mkdir(file_dir) + except EnvironmentError as exp: + message = "Directory {} does not exist, and cannot be created: {}" + raise ValueError(message.format(file_dir, exp)) + if os.path.isfile(file_path): + raise ValueError(f"File {file_path} already exists.") + namespace.destination = file_path # CUSTOM REQUEST VALIDATORS diff --git a/src/azure-cli/azure/cli/command_modules/batchai/custom.py b/src/azure-cli/azure/cli/command_modules/batchai/custom.py index 411de6dc1df..f17a2e3e3f2 100644 --- a/src/azure-cli/azure/cli/command_modules/batchai/custom.py +++ b/src/azure-cli/azure/cli/command_modules/batchai/custom.py @@ -461,7 +461,7 @@ def _get_scale_settings(initial_count, min_count, max_count): if not initial_count and not min_count and not max_count: # Get from the config file return None - if sum([1 if v is not None else 0 for v in (min_count, max_count)]) == 1: + if sum(1 if v is not None else 0 for v in (min_count, max_count)) == 1: raise CLIError('You need to either provide both min and max node counts or not provide any of them') if min_count is not None and max_count is not None and min_count > max_count: raise CLIError('Maximum nodes count must be greater or equal to minimum nodes count') diff --git a/src/azure-cli/azure/cli/command_modules/cosmosdb/_validators.py b/src/azure-cli/azure/cli/command_modules/cosmosdb/_validators.py index 75004c20ce3..5bc1ab06ae0 100644 --- a/src/azure-cli/azure/cli/command_modules/cosmosdb/_validators.py +++ b/src/azure-cli/azure/cli/command_modules/cosmosdb/_validators.py @@ -434,7 +434,7 @@ def validate_client_encryption_policy(ns): "policyFormatVersion is an integer type. " "Supported versions are 1 and 2.") - if(policyFormatVersion < 1 or policyFormatVersion > 2): + if (policyFormatVersion < 1 or policyFormatVersion > 2): raise InvalidArgumentValueError("Invalid policyFormatVersion used in Client Encryption Policy. " "Please verify your Client Encryption Policy JSON string. " "Supported versions are 1 and 2.") @@ -455,7 +455,7 @@ def _validate_included_paths_in_cep(partition_key_path, includedPaths, policyFor raise InvalidArgumentValueError("Invalid encryptionType included in Client Encryption Policy. " "encryptionType cannot be null or empty.") - if(encryptionType != "Deterministic" and encryptionType != "Randomized"): + if (encryptionType != "Deterministic" and encryptionType != "Randomized"): raise InvalidArgumentValueError(f"Invalid Encryption Type {encryptionType} used. " "Supported types are Deterministic or Randomized.") @@ -474,7 +474,7 @@ def _validate_included_paths_in_cep(partition_key_path, includedPaths, policyFor listOfPaths.append(path) - if(path[0] != "/" or path.rfind('/') != 0): + if (path[0] != "/" or path.rfind('/') != 0): raise InvalidArgumentValueError("Invalid path included in Client Encryption Policy. " "Only top level paths supported. Paths should begin with /.") diff --git a/src/azure-cli/azure/cli/command_modules/dms/custom.py b/src/azure-cli/azure/cli/command_modules/dms/custom.py index 130446c578b..7a5a17425e5 100644 --- a/src/azure-cli/azure/cli/command_modules/dms/custom.py +++ b/src/azure-cli/azure/cli/command_modules/dms/custom.py @@ -318,8 +318,7 @@ def get_file_or_parse_json(value, value_type): except Exception as e: raise CLIError("The supplied input for '{type}' is not a valid file path or a valid json object. {ex}'" .format(type=value_type, ex=e)) - else: - return json_parse + return json_parse def create_connection(connection_info_json, prompt_prefix, typeOfInfo): diff --git a/src/azure-cli/azure/cli/command_modules/eventhubs/operations/network_rule_set.py b/src/azure-cli/azure/cli/command_modules/eventhubs/operations/network_rule_set.py index 8e440dc6350..9dea610c96c 100644 --- a/src/azure-cli/azure/cli/command_modules/eventhubs/operations/network_rule_set.py +++ b/src/azure-cli/azure/cli/command_modules/eventhubs/operations/network_rule_set.py @@ -62,7 +62,7 @@ def remove_network_rule_set_ip_rule(cmd, resource_group_name, namespace_name, ip ip_rule_list.append(ip_rule_dict) for i in ip_rule: - for j in ip_rule_list: + for j in ip_rule_list[:]: if i['ip-address'] == j["ip_mask"]: ip_rule_list.remove(j) command_args_dict = { @@ -121,7 +121,7 @@ def remove_virtual_network_rule(cmd, resource_group_name, namespace_name, subnet virtual_network_rule_list.append(subnet_dict) for i in subnet: - for j in virtual_network_rule_list: + for j in virtual_network_rule_list[:]: if i['id'].lower() == j['subnet'].lower(): virtual_network_rule_list.remove(j) command_args_dict = { diff --git a/src/azure-cli/azure/cli/command_modules/keyvault/custom.py b/src/azure-cli/azure/cli/command_modules/keyvault/custom.py index 8f65372388a..76e4947bfbc 100644 --- a/src/azure-cli/azure/cli/command_modules/keyvault/custom.py +++ b/src/azure-cli/azure/cli/command_modules/keyvault/custom.py @@ -1416,7 +1416,7 @@ def download_key(client, file_path, hsm_name=None, identifier=None, # pylint: d 'PEM': _export_public_key_to_pem } - if encoding not in methods.keys(): + if encoding not in methods: raise CLIError('Unsupported encoding: {}. (Supported encodings: DER, PEM)'.format(encoding)) try: diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_workspace.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_workspace.py index 583f3cd91e0..4fbe8ce1c78 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_workspace.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_workspace.py @@ -191,8 +191,8 @@ def create_log_analytics_workspace_table(cmd, resource_group_name, workspace_nam description=None, no_wait=False): if retention_in_days and total_retention_in_days: if total_retention_in_days < retention_in_days: - InvalidArgumentValueError('InvalidArgumentValueError: The specified value of --retention-time' - ' should be less than --total-retention-time') + raise InvalidArgumentValueError('InvalidArgumentValueError: The specified value of --retention-time' + ' should be less than --total-retention-time') columns_list = None if columns: columns_list = [] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/monitor_clone_util.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/monitor_clone_util.py index 4c11b7a53c2..60ce8a9b1a6 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/monitor_clone_util.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/monitor_clone_util.py @@ -28,7 +28,7 @@ def _gen_metrics_alert_rules_clone_list(monitor_client, source_resource, target_ def _add_into_existing_scopes(monitor_client, alert_rule, target_resource): alert_rule.scopes.append(target_resource) - resource_group_name, name = _parse_id(alert_rule.id).values() + resource_group_name, name = _parse_id(alert_rule.id).values() # pylint: disable=unbalanced-dict-unpacking return monitor_client.metric_alerts.create_or_update(resource_group_name=resource_group_name, rule_name=name, parameters=alert_rule) @@ -40,10 +40,10 @@ def _clone_and_replace_action_group(source_monitor_client, target_monitor_client if action.action_group_id in action_group_mapping: alert_rule.actions[index] = action_group_mapping[action.action_group_id][1] else: - resource_group_name, name = _parse_id(action.action_group_id).values() + resource_group_name, name = _parse_id(action.action_group_id).values() # pylint: disable=unbalanced-dict-unpacking action_group = source_monitor_client.action_groups.get(resource_group_name, name) name = CLONED_NAME.format(name, gen_guid()) - resource_group_name, _ = _parse_id(target_resource).values() + resource_group_name, _ = _parse_id(target_resource).values() # pylint: disable=unbalanced-dict-unpacking new_action_group = target_monitor_client.action_groups.create_or_update(resource_group_name, name, action_group) @@ -57,7 +57,7 @@ def _clone_and_replace_action_group(source_monitor_client, target_monitor_client def _clone_alert_rule(monitor_client, alert_rule, target_resource): alert_rule.scopes = [target_resource] - resource_group_name, name = _parse_id(target_resource).values() + resource_group_name, name = _parse_id(target_resource).values() # pylint: disable=unbalanced-dict-unpacking name = CLONED_NAME.format(name, gen_guid()) return monitor_client.metric_alerts.create_or_update(resource_group_name=resource_group_name, rule_name=name, diff --git a/src/azure-cli/azure/cli/command_modules/mysql/_util.py b/src/azure-cli/azure/cli/command_modules/mysql/_util.py index 14ddfdc8b0f..32e582c0652 100644 --- a/src/azure-cli/azure/cli/command_modules/mysql/_util.py +++ b/src/azure-cli/azure/cli/command_modules/mysql/_util.py @@ -491,10 +491,10 @@ def get_user_confirmation(message, yes=False): def replace_memory_optimized_tier(result): result = _get_list_from_paged_response(result) - for capability_idx, capability in enumerate(result): + for capability in result: for edition_idx, edition in enumerate(capability.supported_flexible_server_editions): if edition.name == 'MemoryOptimized': - result[capability_idx].supported_flexible_server_editions[edition_idx].name = 'BusinessCritical' + capability.supported_flexible_server_editions[edition_idx].name = 'BusinessCritical' return result diff --git a/src/azure-cli/azure/cli/command_modules/rdbms/_flexible_server_util.py b/src/azure-cli/azure/cli/command_modules/rdbms/_flexible_server_util.py index fe283a254fc..6f9e9b02dda 100644 --- a/src/azure-cli/azure/cli/command_modules/rdbms/_flexible_server_util.py +++ b/src/azure-cli/azure/cli/command_modules/rdbms/_flexible_server_util.py @@ -434,10 +434,10 @@ def get_user_confirmation(message, yes=False): def replace_memory_optimized_tier(result): result = _get_list_from_paged_response(result) - for capability_idx, capability in enumerate(result): + for capability in result: for edition_idx, edition in enumerate(capability.supported_flexible_server_editions): if edition.name == 'MemoryOptimized': - result[capability_idx].supported_flexible_server_editions[edition_idx].name = 'BusinessCritical' + capability.supported_flexible_server_editions[edition_idx].name = 'BusinessCritical' return result diff --git a/src/azure-cli/azure/cli/command_modules/resource/_packing_engine.py b/src/azure-cli/azure/cli/command_modules/resource/_packing_engine.py index 07b3109de70..a7b09fef3c5 100644 --- a/src/azure-cli/azure/cli/command_modules/resource/_packing_engine.py +++ b/src/azure-cli/azure/cli/command_modules/resource/_packing_engine.py @@ -99,7 +99,7 @@ def _pack_artifacts(cmd, template_abs_file_path, context): # Let's make sure we're not referencing a file outside of our root directory # hierarchy. We won't allow such references for security purposes: - if(not os.path.commonpath([getattr(context, 'RootTemplateDirectory')]) == + if (not os.path.commonpath([getattr(context, 'RootTemplateDirectory')]) == os.path.commonpath([getattr(context, 'RootTemplateDirectory'), abs_local_path])): raise BadRequestError('Unable to handle the reference to file ' + abs_local_path + 'from ' + template_abs_file_path + @@ -144,7 +144,7 @@ def _get_deployment_resource_objects(cmd, template_obj, includeNested=False): results = [] for deployment_resource_obj in immediate_deployment_resources: results.append(deployment_resource_obj) - if(includeNested and 'properties' in deployment_resource_obj): + if (includeNested and 'properties' in deployment_resource_obj): deployment_resource_props_obj = deployment_resource_obj['properties'] if 'mainTemplate' in deployment_resource_props_obj: results.extend(_get_deployment_resource_objects(cmd, diff --git a/src/azure-cli/azure/cli/command_modules/resource/_validators.py b/src/azure-cli/azure/cli/command_modules/resource/_validators.py index 1612b8470cd..58f606bcf67 100644 --- a/src/azure-cli/azure/cli/command_modules/resource/_validators.py +++ b/src/azure-cli/azure/cli/command_modules/resource/_validators.py @@ -98,7 +98,7 @@ def process_deployment_create_namespace(namespace): if [bool(namespace.template_uri), bool(namespace.template_file)].count(True) != 1: raise CLIError('incorrect usage: Chose only one of' ' --template-file FILE | --template-uri URI') - if(bool(namespace.template_uri) or bool(namespace.template_file)): + if (bool(namespace.template_uri) or bool(namespace.template_file)): _validate_deployment_name(namespace) else: _validate_deployment_name_with_template_specs(namespace) diff --git a/src/azure-cli/azure/cli/command_modules/security/custom.py b/src/azure-cli/azure/cli/command_modules/security/custom.py index 8809965a76f..54b1ec88d7e 100644 --- a/src/azure-cli/azure/cli/command_modules/security/custom.py +++ b/src/azure-cli/azure/cli/command_modules/security/custom.py @@ -1137,7 +1137,7 @@ def get_security_automation_rules_object(rules): def sanitize_json_as_string(value: string): valueLength = len(value) - if((value[0] == '\'' and value[valueLength - 1] == '\'') or (value[0] == '\"' and value[valueLength - 1] == '\"')): + if ((value[0] == '\'' and value[valueLength - 1] == '\'') or (value[0] == '\"' and value[valueLength - 1] == '\"')): value = value[1:] value = value[:-1] return value diff --git a/src/azure-cli/azure/cli/command_modules/servicebus/operations/network_rule_set.py b/src/azure-cli/azure/cli/command_modules/servicebus/operations/network_rule_set.py index 7150b9ade05..1f38a7b7b7f 100644 --- a/src/azure-cli/azure/cli/command_modules/servicebus/operations/network_rule_set.py +++ b/src/azure-cli/azure/cli/command_modules/servicebus/operations/network_rule_set.py @@ -59,7 +59,7 @@ def remove_network_rule_set_ip_rule(cmd, resource_group_name, namespace_name, ip ip_rule_list.append(ip_rule_dict) for i in ip_rule: - for j in ip_rule_list: + for j in ip_rule_list[:]: if i['ip-address'] == j["ip_address"]: ip_rule_list.remove(j) command_args_dict = { @@ -119,7 +119,7 @@ def remove_virtual_network_rule(cmd, resource_group_name, namespace_name, subnet virtual_network_rule_list.append(subnet_dict) for i in subnet: - for j in virtual_network_rule_list: + for j in virtual_network_rule_list[:]: if i['id'].lower() == j['subnet'].lower(): virtual_network_rule_list.remove(j) command_args_dict = { diff --git a/src/azure-cli/azure/cli/command_modules/servicefabric/custom.py b/src/azure-cli/azure/cli/command_modules/servicefabric/custom.py index 3a148356c19..1ecb993d14e 100644 --- a/src/azure-cli/azure/cli/command_modules/servicefabric/custom.py +++ b/src/azure-cli/azure/cli/command_modules/servicefabric/custom.py @@ -1392,7 +1392,7 @@ def _get_thumbprint_from_secret_identifier(cli_ctx, vault, secret_identifier): x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert_bytes) if not x509: - raise Exception('invalid certificate') + raise Exception('invalid certificate') # pylint: disable=broad-exception-raised thumbprint = x509.digest("sha1").decode("utf-8").replace(':', '') return thumbprint diff --git a/src/azure-cli/azure/cli/command_modules/servicefabric/operations/managed_clusters.py b/src/azure-cli/azure/cli/command_modules/servicefabric/operations/managed_clusters.py index f85d07fc458..08e5b563989 100644 --- a/src/azure-cli/azure/cli/command_modules/servicefabric/operations/managed_clusters.py +++ b/src/azure-cli/azure/cli/command_modules/servicefabric/operations/managed_clusters.py @@ -153,7 +153,7 @@ def add_client_cert(cmd, issuer_thumbprint = ','.join(issuer_thumbprint) cluster.clients.append(ClientCertificate(is_admin=is_admin, common_name=common_name, issuer_thumbprint=issuer_thumbprint)) else: - CLIError("Thumbprint and Common name are empty") + raise CLIError("Thumbprint and Common name are empty") poller = client.managed_clusters.begin_create_or_update(resource_group_name, cluster_name, cluster) return LongRunningOperation(cmd.cli_ctx)(poller) diff --git a/src/azure-cli/azure/cli/command_modules/sql/custom.py b/src/azure-cli/azure/cli/command_modules/sql/custom.py index ed7e1e56d2b..a8e6d9eaf2d 100644 --- a/src/azure-cli/azure/cli/command_modules/sql/custom.py +++ b/src/azure-cli/azure/cli/command_modules/sql/custom.py @@ -3481,7 +3481,7 @@ def db_sensitivity_label_update( sensitivity_label.information_type_id = current_label.information_type_id except ResourceNotFoundError as ex: - if not(ex and 'SensitivityLabelsLabelNotFound' in str(ex)): + if not (ex and 'SensitivityLabelsLabelNotFound' in str(ex)): raise ex # Find the label id and information type id in the policy by the label name provided diff --git a/src/azure-cli/azure/cli/command_modules/sqlvm/_validators.py b/src/azure-cli/azure/cli/command_modules/sqlvm/_validators.py index ed51cfb2982..90738f3243e 100644 --- a/src/azure-cli/azure/cli/command_modules/sqlvm/_validators.py +++ b/src/azure-cli/azure/cli/command_modules/sqlvm/_validators.py @@ -522,7 +522,7 @@ def _find_role_id(cli_ctx): # This in fact shoud not happen. if len(app_role_id_map) < 3: requird_role_defs = [USER_READ_ALL, APPLICATION_READ_ALL, GROUP_MEMBER_READ_ALL] - missing_role_defs = [role for role in requird_role_defs if role not in app_role_id_map.keys()] + missing_role_defs = [role for role in requird_role_defs if role not in app_role_id_map] error_message = "Querying Microsoft Graph API failed to find the following roles: %s.", ", ".join(missing_role_defs) logger.warning(error_message) diff --git a/src/azure-cli/azure/cli/command_modules/storage/_validators.py b/src/azure-cli/azure/cli/command_modules/storage/_validators.py index 423372f652b..2632b0c3d5d 100644 --- a/src/azure-cli/azure/cli/command_modules/storage/_validators.py +++ b/src/azure-cli/azure/cli/command_modules/storage/_validators.py @@ -2013,7 +2013,7 @@ def _add_sas_for_url(cmd, url, account_name, account_key, sas_token, service, re logger.info("Cannot generate sas token. %s", ex) sas_token = None if sas_token: - return'{}?{}'.format(url, sas_token) + return '{}?{}'.format(url, sas_token) return url diff --git a/src/azure-cli/azure/cli/command_modules/storage/azcopy/util.py b/src/azure-cli/azure/cli/command_modules/storage/azcopy/util.py index afe475d522c..b0b6fba51da 100644 --- a/src/azure-cli/azure/cli/command_modules/storage/azcopy/util.py +++ b/src/azure-cli/azure/cli/command_modules/storage/azcopy/util.py @@ -110,7 +110,7 @@ def login_auth_for_azcopy(cmd): try: token_info = _unserialize_non_msi_token_payload(token_info) except KeyError: # unserialized MSI token payload - raise Exception('MSI auth not yet supported.') + raise Exception('MSI auth not yet supported.') # pylint: disable=broad-exception-raised return AzCopyCredentials(token_info=token_info) @@ -134,7 +134,7 @@ def client_auth_for_azcopy(cmd, client, service='blob'): def storage_client_auth_for_azcopy(client, service): if service not in SERVICES: - raise Exception('{} not one of: {}'.format(service, str(SERVICES))) + raise Exception('{} not one of: {}'.format(service, str(SERVICES))) # pylint: disable=broad-exception-raised if client.sas_token: return AzCopyCredentials(sas_token=client.sas_token) diff --git a/src/azure-cli/azure/cli/command_modules/storage/operations/account.py b/src/azure-cli/azure/cli/command_modules/storage/operations/account.py index 5285a41a60a..b8cac3f5401 100644 --- a/src/azure-cli/azure/cli/command_modules/storage/operations/account.py +++ b/src/azure-cli/azure/cli/command_modules/storage/operations/account.py @@ -497,8 +497,8 @@ def update_storage_account(cmd, instance, sku=None, tags=None, custom_domain=Non if enable_files_adds is not None: ActiveDirectoryProperties = cmd.get_models('ActiveDirectoryProperties') if enable_files_adds: # enable AD - if not(domain_name and net_bios_domain_name and forest_name and domain_guid and domain_sid and - azure_storage_sid): + if not (domain_name and net_bios_domain_name and forest_name and domain_guid and domain_sid and + azure_storage_sid): raise CLIError("To enable ActiveDirectoryDomainServicesForFile, user must specify all of: " "--domain-name, --net-bios-domain-name, --forest-name, --domain-guid, --domain-sid and " "--azure_storage_sid arguments in Azure Active Directory Properties Argument group.") diff --git a/src/azure-cli/azure/cli/command_modules/storage/operations/table.py b/src/azure-cli/azure/cli/command_modules/storage/operations/table.py index 3f720a58812..d839af418da 100644 --- a/src/azure-cli/azure/cli/command_modules/storage/operations/table.py +++ b/src/azure-cli/azure/cli/command_modules/storage/operations/table.py @@ -56,7 +56,7 @@ def list_tables(client, num_results=None, marker=None, show_next_marker=None): def exists(client, table_name): generator = client.query_tables("TableName eq '{}'".format(table_name)) - return list(next(generator.by_page())) != [] + return bool(list(next(generator.by_page()))) # pylint: disable=redefined-builtin diff --git a/src/azure-cli/azure/cli/command_modules/synapse/manual/operations/sqlpoolsensitivitylabel.py b/src/azure-cli/azure/cli/command_modules/synapse/manual/operations/sqlpoolsensitivitylabel.py index 1783baaa47d..1b1cb068628 100644 --- a/src/azure-cli/azure/cli/command_modules/synapse/manual/operations/sqlpoolsensitivitylabel.py +++ b/src/azure-cli/azure/cli/command_modules/synapse/manual/operations/sqlpoolsensitivitylabel.py @@ -70,7 +70,7 @@ def sqlpool_sensitivity_label_update( sensitivity_label.information_type_id = current_label.information_type_id except CloudError as ex: - if not(ex.error and ex.error.error and 'SensitivityLabelsLabelNotFound' in ex.error.error): + if not (ex.error and ex.error.error and 'SensitivityLabelsLabelNotFound' in ex.error.error): raise ex # Find the label id and information type id in the policy by the label name provided diff --git a/src/azure-cli/azure/cli/command_modules/vm/custom.py b/src/azure-cli/azure/cli/command_modules/vm/custom.py index 01ad9a4fdd8..7f44d13a10a 100644 --- a/src/azure-cli/azure/cli/command_modules/vm/custom.py +++ b/src/azure-cli/azure/cli/command_modules/vm/custom.py @@ -2917,7 +2917,7 @@ def remove_vm_secret(cmd, resource_group_name, vm_name, keyvault, certificate=No cert_url_pattern = '/' + cert_url_pattern + '/' for x in temp: x.vault_certificates = ([v for v in x.vault_certificates - if not(v.certificate_url and cert_url_pattern in v.certificate_url.lower())]) + if not (v.certificate_url and cert_url_pattern in v.certificate_url.lower())]) to_keep = [x for x in to_keep if x.vault_certificates] # purge all groups w/o any cert entries vm.os_profile.secrets = to_keep